有時須要設定未來發生的事情,這時該怎麼辦?ActorSystem搞定一切! 在那兒你能找到scheduler方法,它返回一個 akka.actor.Scheduler 實例, 這個實例在每一個Actor系統裏是惟一的,用來指定一段時間後發生的行爲。請注意定時任務是使用ActorSystem的MessageDispatcher執行的. html
你能夠計劃向actor發送消息或執行任務的代碼 (函數或Runnable). 你會獲得一個Cancellable類型的返回值,你能夠調用cancel來取消定時任務的執行。 api
package controllers import play.api._ import play.api.mvc._ import play.libs.Akka import akka.actor._ import scala.concurrent.duration._ import play.api.libs.concurrent.Execution.Implicits._ object Application extends Controller { def index = Action { // say hello Logger.info("hello, index action started") val Tick = "tick" val Tack = "tack" val tickActor = Akka.system.actorOf(Props(new Actor { def receive = { case Tick => Logger.info("that still ticks!") case Tack => Logger.warn("... 7 seconds after start, only once") } })) // Repeat every 5 seconds, start 5 seconds after start Akka.system.scheduler.schedule( 5 seconds, 5 seconds, tickActor, Tick ) // do only once, 7 seconds after start Akka.system.scheduler.scheduleOnce(7 seconds, tickActor, Tack) Ok(views.html.index("Your new application is ready.")) } }