Motoko | Jazz heartbeat

It is my pleasure to introduce you :drum: Jazz :saxophone: made @ Anvil Research - a small repo demonstrating a new spooky pattern.

Example - delay

  // Our function using jazz.delay
  public shared({caller}) func first_example() : async () {

    var unforgettable = "Something else"; 
  
    // This function will execute after 5 seconds
    jazz.delay(5, func() : () {
      unforgettable := unforgettable # " Whee"; // our delayed function will have access to parent scope variable 
      te := unforgettable; // lets set te so the public get function can confirm our function executed
    });

  // this function will exit right away, wont wait for delay
  };

Example - retry


  //Our function using jazz.retry. To see it in action, repeatedly call 'get' function after calling `second_example`
  public shared({caller}) func second_example() : async () {

    te := "Let's go..."; 

    // This function will execute up to 3 times with 5 seconds interval. If it returns `true` there will be no more retrying
    ignore jazz.retry(3, 5, func() : async Bool {
      te := te # " # "; 

      false;
    });

  // this function will exit after first try, rest will run later
  };

How does it work

Anonymous functions are added to memory. Heartbeat executes them later.
Currently it’s for demo purposes and to help IC figure how to improve heartbeat @ulan. This suggested solution will probably work best for this pattern ic0.pause_heartbeat_until(absolute_time)
Doesn’t have a very good memory management and costs a lot.
You can use the pattern in production if you truly understand whats happening under the hood.

Usecase

These will be pretty useful when trying to solve tokenization related problems. @mariop For example - when notifying other canisters or adding transactions to history.

Future

These are possible: Throttle, Interval, Debounce, Cron, Batch, Shared async callback, etc…

It makes a lot of new things possible.

12 Likes

Awesome @infu ! Great work. Can’t wait to see what is under the hood.

2 Likes

Actually found a way to mock time and test various cases.

prints