dfinity / motoko-base

The Motoko base library
Apache License 2.0
483 stars 99 forks source link

Recurring Timer Cancelling #634

Closed Gekctek closed 6 months ago

Gekctek commented 6 months ago

So I am running into an issue where I want to cancel a recurring timer from INSIDE the timer function itself But i dont see a way where the recurring timer function has context of the timerid

I kinda have a work around where i do a lookup of an id that I had beforehand, but its not 100% foolproof. Is there a way to do this that Im not seeing?

I think having the id context in the func would be helpful, or maybe a return type that specifies if the timer should stop or not

Timer.recurringTimer<system>(
            #seconds(5),
            func() : async () {
                switch (doSomthing()) {
                        case (#ok) ();
                        case (#stop) Timer.cancelTimer(???);
                    };
            },
        );
chenyan-dfinity commented 6 months ago

How about using setTimer?

  func job() : async () {
    switch (doSomthing()) {
      case (#ok) {
        Timer.setTimer(#seconds(5), job);
      };
      case (#stop) ();
    };
  };
  Timer.setTimer<system>(#seconds(5), job);
Gekctek commented 6 months ago

Interesting idea that might work, but if it got interrupted with a upgrade or an error it would just stop right? Maybe if I track the latest timerId, but then we are in a similar issue as before

chenyan-dfinity commented 6 months ago

Yep, you can store the latest id in a global state. What's the issue for that?

Gekctek commented 6 months ago

Ill try the Timer.setTimer idea and ill see if I have any issues. Thanks