定时器和提醒器

Orleans提供两种调度机制,定时器和提醒器,使开发者能够定义Grain的周期性行为。

定时器(Timers)

定时器描述

定时器适用于在不需要考虑Grain被多次激活(即Grain实例化)的时候,创建Grain周期性的行为。它本质上和.NET的类库System.Threading.Time是一回事。此外,定时器会受其操作的Grain在激活期间的单线程执行(single threaded execution)保证的约束。
Grain的每一次激活,都可能有零个或多个与之相关的定时器。在Grain被激活时,Orleans运行时会在激活的运行时上下文之内,执行每个与本次激活相关的定时器(The runtime executes each timer routine within the runtime context of the activation that it is associated with)。

定时器使用

使用Grain.RegisterTime方法来开启一个定时器,该方法返回值类型为IDisposable接口。

  1. public IDisposable RegisterTimer(
  2. Func<object, Task> asyncCallback, // function invoked when the timer ticks
  3. object state, // object tp pass to asyncCallback
  4. TimeSpan dueTime, // time to wait before the first timer tick
  5. TimeSpan period) // the period of the timer

调用上面方法返回的引用的Dispose方法即可关闭定时器。
当激活被中止或故障导致筒仓崩溃时,定时器不再会被触发。
重要的注意事项:

  • 启用激活收集(activation collection)后,执行定时器的回调方法不会把激活状态从空闲(idle)改为使用中(in use)。这意味着定时器不能用于推迟将处于idle状态的已激活Grain的失活的操作。

提醒器(Reminders)

提醒器描述

配置

提醒器使用

如何选择调度机制

定时器和提醒器配合使用