How to schedule task daily + onStart() in Play 2.0.4?

转载 2015年11月18日 14:48:00

I need to execute a piece of code 1 time everyday in playframework2.0.4 when I try to do with the class extends GlobalSettings it works. But it works for every instance requesting. I want it works when server starts and does its duty everyday 1 time.

package controllers;
import java.util.concurrent.TimeUnit;
import akka.util.Duration;
import play.Application;
import play.GlobalSettings;
import play.libs.Akka;

public class ParserJobApp extends GlobalSettings{
public void onStart(Application app) {
    Akka.system().scheduler().schedule(Duration.create(0, TimeUnit.MILLISECONDS),Duration.create(6, TimeUnit.SECONDS), new Runnable() {
        public void run() {
            System.out.println("AAA ---    "+System.currentTimeMillis());

And this is my controller where start the class above

public class Application extends Controller {

public static Result index() {
  ParserJobApp pr=new ParserJobApp();
return ok(index.render("Your new "));


java playframework-2.0 akka scheduler
shareimprove this question
edited Feb 5 '13 at 12:50
asked Feb 5 '13 at 11:19


This version of schedule() seems to have been removed in 2.1, how do you this in play 2.1? – nylund Mar 25 '13 at 18:34

Nevermind, I just found it. It now takes 4 arguments and the last being the execution contexts, Akka.system().dispatcher(). – nylund Mar 25 '13 at 18:35
add a comment
2 Answers
active oldest votes
up vote 16 down vote accepted

Scheduler tasks should be placed only in Global class. Create two tasks, schedule only once first with initialDelay = 0 milliseconds.

For second task, you need to calculate seconds between current DateTime and next planned occurence (ie. tommorow at 8:00 o'clock) using common date/time classes, then set this difference as initialDelay and also set frequency to 24 hours.

In result it will start at the application start, and will schedule task for execution each day at required hour.


There's complete sample, (save/edit the class: /app/

import akka.util.Duration;
import org.joda.time.DateTime;
import org.joda.time.Seconds;
import play.Application;
import play.GlobalSettings;
import play.Logger;
import play.libs.Akka;
import java.util.concurrent.TimeUnit;

public class Global extends GlobalSettings {

    public void onStart(Application application) {

                Duration.create(0, TimeUnit.MILLISECONDS),
                new Runnable() {
                    public void run() {
              "ON START ---    " + System.currentTimeMillis());

                Duration.create(nextExecutionInSeconds(8, 0), TimeUnit.SECONDS),
                Duration.create(24, TimeUnit.HOURS),
                new Runnable() {
                    public void run() {
              "EVERY DAY AT 8:00 ---    " + System.currentTimeMillis());

    public static int nextExecutionInSeconds(int hour, int minute){
        return Seconds.secondsBetween(
                new DateTime(),
                nextExecution(hour, minute)

    public static DateTime nextExecution(int hour, int minute){
        DateTime next = new DateTime()

        return (next.isBeforeNow())
                ? next.plusHours(24)
                : next;

shareimprove this answer
edited Feb 5 '13 at 14:43

answered Feb 5 '13 at 11:44


every time I call localhost:9000 the task works again. So it means it is going to work when every user make a request. Is it not possible to start task one at the time app starts? I created the instance of Global class in controller class in index() method as Global gl=new Global(); gl.onStart(null); – gabby Feb 5 '13 at 13:51
I gave you whole Global class, just save it as /app/ and DON'T create ANY instances in your action(s) – biesior Feb 5 '13 at 14:05

Thank you. It works – gabby Feb 5 '13 at 14:15
I realized that as well after answering : there's a comment: 'it MUST execute all outstanding tasks upon .close() in order to properly shutdown all dispatchers.', and probably that causes the last execution. If you won't find any solution it's good topic for new question (I'm interested with this to, but have no time now) – biesior Feb 5 '13 at 14:39
Ok, so, this is how I did: Cancellable scheduler = Akka.system().scheduler().schedule(....); and create: @Override public void onStop(Application application) { scheduler.cancel(); } – Tyrael Aug 7 '14 at 12:56
show 4 more comments
up vote 12 down vote

Here is my solution which is lighter and supports cron expressions for scheduling. In this example, the scheduler will run everyday at 10:00 AM.

Following in your Global class:

private Cancellable scheduler;

public void onStart(Application application) {

public void onStop(Application application) {
    //Stop the scheduler
    if (scheduler != null) {

private void schedule() {
    try {
        CronExpression e = new CronExpression("0 00 10 ? * *");
        Date nextValidTimeAfter = e.getNextValidTimeAfter(new Date());
        FiniteDuration d = Duration.create(
            nextValidTimeAfter.getTime() - System.currentTimeMillis(),

        Logger.debug("Scheduling to run at "+nextValidTimeAfter);

        scheduler = Akka.system().scheduler().scheduleOnce(d, new Runnable() {

        public void run() {
            Logger.debug("Ruuning scheduler");
            //Do your tasks here

            schedule(); //Schedule for next time

        }, Akka.system().dispatcher());
    } catch (Exception e) {
        Logger.error("", e);

How to develop and deploy DNN Schedule Task

九月 19, 2011 15:15 by                Naveen Every now and then we all run into development of fun...

How to play video in cocos2dx with DirectShow

How to play video in cocos2dx with DirectShow   The purpose of this article is to illustrate how to ...

How to Play, Record, and Edit Videos in iOS

This is a blog post by iOS Tutorial Team member Abdul Azeem, software architect and co-founder at ...

How to play an AVI in a status bar.

  • 2006年02月23日 09:05
  • 119KB
  • 下载

How to create a task in the openwrt system, the timer to switch WiFi power。


[How to expression urself clearly and completely] Daily Life

1. Listen to yourself.  Self expression, which is the ability to communicate and demonstrate your fe...

Daily Deposit Bonus Up To MYR300 in iBET Online Casino

iBET Online Casino Malaysia great November Daily Deposit Bonus Promotion for all members who have pl...

How to play a video file?

VideoIO Flash-based audio and video communication Home › Flash-VideoIO Tutorial ...

【cocos2d-x IOS游戏开发-城市跑酷13】游戏玩法:友情提示:how to play?

尊重开发者的劳动成果,转载的时候请务必注明出处: >回顾 【cocos2d...

How to play BreakerBall game on DragonBoard 410c ?

基本配置要求 1、一个大于1G的SD卡(用来在DragonBoard 410c上安装Debian); 2、DragonBoard410C 3、HDMI线缆 4、USB 键盘、USB鼠标一套 5、U盘一...
您举报文章:How to schedule task daily + onStart() in Play 2.0.4?