Heartbeats案例

Heartbeats

Internet Computer canisters can elect to receive regular heartbeat messages by exposing a particular canister_heartbeat function (see heartbeat).

互联网计算机容器可以通过公开特定的 canister_heartbeat 函数(请参阅 heartbeat)来选择定期接收心跳消息。

In Motoko, an actor can receive heartbeat messages by declaring a system function, named heartbeat, with no arguments, returning a future of unit type (async ()).

在 Motoko 中,actor 可以通过声明一个名为 heartbeat 的系统函数来接收心跳消息,该函数不带任何参数,返回单位类型的 future (async ())。

A simple, contrived example is a recurrent alarm, that sends a message to itself every n-th heartbeat:

一个简单的、人为的例子是一个循环警报,它每第 n 个心跳就向自身发送一条消息:

import Debug "mo:base/Debug";

actor {

  let n = 5;
  var count = 0;

  public shared func ring() : async () {
    Debug.print("Ring!");
  };

  system func heartbeat() : async () {
    if (count % n == 0) {
      await ring();
    };
    count += 1;
  }
}

The heartbeat function, when declared, is called on every Internet Computer subnet heartbeat, by scheduling an asynchronous call to the heartbeat function. Due to its async return type, a heartbeat function may send further messages and await results. The result of a heartbeat call, including any trap or thrown error, is ignored. The implicit context switch inherent to calling every Motoko async function, means that the time the heartbeat body is executed may be later than the time the heartbeat was issued by the subnet.

声明heartbeat函数后,会通过调度对心跳函数的异步调用,在每个互联网计算机子网心跳上调用心跳函数。 由于其异步返回类型,心跳函数可能会发送更多消息并等待结果。 心跳调用的结果(包括任何陷阱或抛出的错误)将被忽略。 调用每个 Motoko 异步函数所固有的隐式上下文切换意味着执行心跳主体的时间可能晚于子网发出心跳的时间。

As an async function, Alarm's heartbeat function is free to call other asynchronous functions (the inner call to ring() above is an example), as well as shared functions of other canisters.

作为一个异步函数,Alarm 的心跳函数可以自由调用其他异步函数(上面对ring() 的内部调用是一个示例),以及其他容器的共享函数。

Heartbeats案例
arkMeta Crypto Network Limited, arkSong 2023年10月28日
标签
登录 留下评论

Motoko 智能合约语言的简明概述
Concise overview of Motoko