Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a scheduled job at specific date in Play 2.0?

Where is the job support in Play 2.0?

I have read this thread and found the way to implement scheduled jobs at intervals using Global and Akka.

But still have no idea with a scheduled job at a specifc date, for example, a job executed once a day at midnight.

Play 2.0 doesn't support it? If not, what is the best way?

like image 516
tototoshi Avatar asked Mar 27 '12 04:03

tototoshi


2 Answers

You could use the Quartz library with the CronTrigger to execute Jobs at a specific date/time. Have a look at their tutorial. Here is an example with a simple scheduler:

import java.util.Date

import org.quartz.JobBuilder.newJob
import org.quartz.SimpleScheduleBuilder.simpleSchedule
import org.quartz.TriggerBuilder.newTrigger
import org.quartz.impl.StdSchedulerFactory
import org.quartz.Job
import org.quartz.JobExecutionContext

import play.api.Application
import play.api.GlobalSettings
import play.api.Logger

object Global extends GlobalSettings {

  val scheduler = StdSchedulerFactory.getDefaultScheduler();

  override def onStart(app: Application) {
    Logger.info("Quarz scheduler starting...")

    scheduler.start();

    // define the job and tie it to our HelloJob class
    val job = newJob(classOf[MyWorker]).withIdentity("job1", "group1").build();

    // Trigger the job to run now, and then repeat every 10 seconds
    val trigger = newTrigger()
      .withIdentity("trigger1", "group1")
      .startNow()
      .withSchedule(simpleSchedule()
        .withIntervalInSeconds(10)
        .repeatForever())
      .build();

    // Tell quartz to schedule the job using our trigger
    scheduler.scheduleJob(job, trigger);

  }

  override def onStop(app: Application) {
    Logger.info("Quartz scheduler shutdown.")
    scheduler.shutdown();
  }

}

class MyWorker extends Job {
  def execute(ctxt: JobExecutionContext) {
    Logger.debug("Scheduled Job triggered at: " + new Date)
  }
}
like image 132
sunsations Avatar answered Nov 10 '22 04:11

sunsations


Try Deadline in Akka?

"Durations have a brother name Deadline, which is a class holding a representation of an absolute point in time, and support deriving a duration from this by calculating the difference between now and the deadline."

like image 30
fxp Avatar answered Nov 10 '22 05:11

fxp