Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to schedule an hourly job with Play Framework 2.1?

In Play 1 it was simply:

@Every(value = "1h")
public class WebsiteStatusReporter extends Job {

    @Override
    public void doJob() throws Exception {
        // do something
    }
}

What is the equivalent for Play 2.1?

I know that Play uses akka and I found this code sample:

import play.api.libs.concurrent.Execution.Implicits._
Akka.system.scheduler.schedule(0.seconds, 30.minutes, testActor, "tick")

But being a Scala noob I don't understand how works. Can someone provide a complete, working example (end to end)?

like image 583
ripper234 Avatar asked Feb 25 '13 18:02

ripper234


Video Answer


1 Answers

Here is an extract from a 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")
  }

}

It simply starts a daemon at the start of the app, and then, every 5 minutes. It uses Play 2.1 and it works as expected.

Note that this code uses the Global object which allows to run some code on application startup.

like image 107
ndeverge Avatar answered Sep 26 '22 22:09

ndeverge