代码之家  ›  专栏  ›  技术社区  ›  ripper234 Jonathan

如何使用Play Framework 2.1安排小时工作?

  •  13
  • ripper234 Jonathan  · 技术社区  · 13 年前

    在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的傻瓜,我不明白它是如何运作的。有人能提供一个完整的、有效的例子(端到端)吗?

    4 回复  |  直到 13 年前
        1
  •  22
  •   ndeverge    13 年前

    这是摘录自 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 这允许在应用程序启动时运行一些代码。

        2
  •  4
  •   EECOLOR    13 年前

    例如:

    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)
    
        3
  •  3
  •   Community Mohan Dere    9 年前

    看看 Akka's doc

    您提供的样本是:

    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
    

    More detailed description in other answer

        4
  •  -1
  •   binshi    10 年前

    一个不使用Actors的简单播放调度程序。

    这可以使用org.quartz.scheller并从Global类调用调度器来完成。

    Sample scheduler

    推荐文章