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?
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)
}
}
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With