Internet Computer canisters can set an arbitrary number of single-expiration or recurring timers. See the Timer.mo module in the base library.
互联网计算机容器可以设置任意数量的单次到期或循环定时器。 请参阅基础库中的 https://timer.mo/ 模块。
A simple, contrived example is a periodic reminder, that logs a new-year's message:
一个简单的、人为的例子是定期提醒,记录新年消息:
import { print } = "mo:base/Debug"; import { abs } = "mo:base/Int"; import { now } = "mo:base/Time"; import { setTimer; recurringTimer } = "mo:base/Timer"; actor Reminder{ let solarYearSeconds = 356_925_216; private func remind() : async () { print("Happy New Year!"); }; ignore setTimer(#seconds (solarYearSeconds - abs(now() / 1_000_000_000) % solarYearSeconds), func () : async () { ignore recurringTimer(#seconds solarYearSeconds, remind); await remind(); }); }
The underlying mechanism is a canister global timer that, by default, is issued with appropriate callbacks from a priority queue maintained by the Motoko runtime.
底层机制是Canister容器全局计时器,默认情况下,它是通过 Motoko 运行时维护的优先级队列中的适当回调发出的。
The timer mechanism can be disabled completely by passing the -no-timer flag to moc.
When lower-level access to the canister global timer is desired, an actor can elect to receive timer expiry messages by declaring a system function, named timer. The function takes one argument (to re-set the global timer), and returns a future of unit type (async ()). If the timer system method is declared, the Timer.mo base library module may not function correctly and should not be used.
通过将 -no-timer 标志传递给 moc 可以完全禁用计时器机制。
当需要对容器全局计时器进行较低级别的访问时,参与者可以通过声明名为计时器的系统函数来选择接收计时器到期消息。 该函数采用一个参数(用于重新设置全局计时器),并返回单位类型的 future (async ())。 如果声明了计时器系统方法,https://timer.mo/ 基础库模块可能无法正常运行,因此不应使用。
The following example of a global timer expiration callback gets called immediately after the canister starts (i.e. after install) and periodically every twenty seconds thereafter:
system func timer(setGlobalTimer : Nat64 -> ()) : async () { let next = Nat64.fromIntWrap(Time.now()) + 20_000_000_000; setGlobalTimer(next); // absolute time in nanoseconds print("Tick!"); }
Timers定时器编程案例