调度器

    有时需要设定将来发生的事情,这时该怎么办? ActorSystem 就能搞定一切! 在那儿你能找到 scheduler 方法,它返回一个 akka.actor.Scheduler 实例, 这个实例在每个Actor系统里是唯一的,用来在内部指定一段时间后发生的行为。

    请注意定时任务是使用 ActorSystem 的 MessageDispatcher 执行的.

    你可以计划向actor发送消息或执行任务 (函数或Runnable). 你会得到一个 Cancellable 类型的返回值,你可以调用 cancel 来取消定时操作的执行。

    1. //Schedules a function to be executed (send a message to the testActor) after 50ms
    2. system.scheduler.scheduleOnce(50 milliseconds) {
    3. testActor ! System.currentTimeMillis
    4. }
    1. /**
    2. * Light-weight scheduler for running asynchronous tasks after some deadline
    3. * in the future. Not terribly precise but cheap.
    4. def scheduler: Scheduler

    它使你可以 取消 计划执行的任务。

    警告
    它不会中止已经启动的任务的执行。

    调度的任务会返回一个 Cancellable (或抛出IllegalStateException时,如果在调度器关闭后尝试使用)。这允许你取消原定执行的东西。

    1. /**
    2. * Signifies something that can be cancelled
    3. * There is no strict guarantee that the implementation is thread-safe,
    4. * but it should be good practice to make it so.
    5. */
    6. /**
    7. * Cancels this Cancellable and returns true if that was successful.
    8. * If this cancellable was (concurrently) cancelled already, then this method
    9. * will return false although isCancelled will return true.
    10. * Java & Scala API
    11. */
    12. def cancel(): Boolean
    13. /**
    14. * Returns true if and only if this Cancellable has been successfully cancelled
    15. *
    16. * Java & Scala API
    17. */
    18. def isCancelled: Boolean