在Play 1中,它只是:
@Every(value = "1h")
public class WebsiteStatusReporter extends Job {
@Override
public void doJob() throws Exception {
// do something
}
}
Play 2.1的等效内容是什么?
我知道Play使用了akka和我found this code sample:
import play.api.libs.concurrent.Execution.Implicits._
Akka.system.scheduler.schedule(0.seconds, 30.minutes, testActor, "tick")
但是作为Scala noob,我不明白它是如何运作的。有人可以提供一个完整的,有效的例子(端到端)吗?
答案 0 :(得分:22)
以下是code of mine:
的摘录import scala.concurrent.duration.DurationInt
import akka.actor.Props.apply
import play.api.Application
import play.api.GlobalSettings
import play.api.Logger
import play.api.Play
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.concurrent.Akka
import akka.actor.Props
import actor.ReminderActor
object Global extends GlobalSettings {
override def onStart(app: Application) {
val controllerPath = controllers.routes.Ping.ping.url
play.api.Play.mode(app) match {
case play.api.Mode.Test => // do not schedule anything for Test
case _ => reminderDaemon(app)
}
}
def reminderDaemon(app: Application) = {
Logger.info("Scheduling the reminder daemon")
val reminderActor = Akka.system(app).actorOf(Props(new ReminderActor()))
Akka.system(app).scheduler.schedule(0 seconds, 5 minutes, reminderActor, "reminderDaemon")
}
}
它只是在应用程序启动时启动守护程序,然后每5分钟启动一次守护程序。它使用Play 2.1,它按预期工作。
请注意,此代码使用Global object,允许在应用程序启动时运行一些代码。
答案 1 :(得分:4)
一个例子:
case object Tick
class TestActor extends Actor {
def receive = {
case Tick => //...
}
}
val testActor = Akka.system.actorOf(Props[TestActor], name = "testActor")
Akka.system.scheduler.schedule(0.seconds, 30.minutes, testActor, Tick)
答案 2 :(得分:3)
def schedule(
initialDelay: Duration,
frequency: Duration,
receiver: ActorRef,
message: Any): Cancellable
表示:从现在开始0秒,每隔30分钟发送给演员testActor
消息Tick
对于你可能没有的简单任务更有用;需要使用Actors - 你可以只安排新的Runnable:
def schedule(
initialDelay: Duration, frequency: Duration, runnable: Runnable): Cancellable
答案 3 :(得分:-1)