调度器
有时需要设定将来发生的事情,这时该怎么办? ActorSystem
就能搞定一切! 在那儿你能找到 scheduler
方法,它返回一个 akka.actor.Scheduler
实例, 这个实例在每个Actor系统里是唯一的,用来在内部指定一段时间后发生的行为。
请注意定时任务是使用 ActorSystem 的 MessageDispatcher 执行的.
你可以计划向actor发送消息或执行任务 (函数或Runnable). 你会得到一个 Cancellable
类型的返回值,你可以调用 cancel
来取消定时操作的执行。
//Schedules a function to be executed (send a message to the testActor) after 50ms
system.scheduler.scheduleOnce(50 milliseconds) {
testActor ! System.currentTimeMillis
}
/**
* Light-weight scheduler for running asynchronous tasks after some deadline
* in the future. Not terribly precise but cheap.
def scheduler: Scheduler
它使你可以 取消 计划执行的任务。
警告
它不会中止已经启动的任务的执行。
调度的任务会返回一个 Cancellable
(或抛出IllegalStateException
时,如果在调度器关闭后尝试使用)。这允许你取消原定执行的东西。
/**
* Signifies something that can be cancelled
* There is no strict guarantee that the implementation is thread-safe,
* but it should be good practice to make it so.
*/
/**
* Cancels this Cancellable and returns true if that was successful.
* If this cancellable was (concurrently) cancelled already, then this method
* will return false although isCancelled will return true.
* Java & Scala API
*/
def cancel(): Boolean
/**
* Returns true if and only if this Cancellable has been successfully cancelled
*
* Java & Scala API
*/
def isCancelled: Boolean