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{
@Override
public void onStart(Application app) {
    Akka.system().scheduler().schedule(Duration.create(0, TimeUnit.MILLISECONDS),Duration.create(6, TimeUnit.SECONDS), new Runnable() {
        @Override
        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();
  pr.onStart(null);
  System.out.println("sfsdfsdf");
return ok(index.render("Your new "));

}
}

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

    

    
    
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.

Edit

There's complete sample, (save/edit the class: /app/Global.java):

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 {

    @Override
    public void onStart(Application application) {


        Akka.system().scheduler().scheduleOnce(
                Duration.create(0, TimeUnit.MILLISECONDS),
                new Runnable() {
                    @Override
                    public void run() {
                        Logger.info("ON START ---    " + System.currentTimeMillis());
                    }
                }
        );

        Akka.system().scheduler().schedule(
                Duration.create(nextExecutionInSeconds(8, 0), TimeUnit.SECONDS),
                Duration.create(24, TimeUnit.HOURS),
                new Runnable() {
                    @Override
                    public void run() {
                        Logger.info("EVERY DAY AT 8:00 ---    " + System.currentTimeMillis());
                    }
                }
        );
    }

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

    public static DateTime nextExecution(int hour, int minute){
        DateTime next = new DateTime()
                .withHourOfDay(hour)
                .withMinuteOfHour(minute)
                .withSecondOfMinute(0)
                .withMillisOfSecond(0);

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

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

    
answered Feb 5 '13 at 11:44
biesior
39k660112

    

    
    
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
1     
    
I gave you whole Global class, just save it as /app/Global.java 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
2     
    
I realized that as well after answering : doc.akka.io/docs/akka/2.0/java/scheduler.html 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
3     
    
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;

@Override
public void onStart(Application application) {
    super.onStart(application);
    schedule();
}

@Override
public void onStop(Application application) {
    //Stop the scheduler
    if (scheduler != null) {
        scheduler.cancel();
    }
}

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(),
            TimeUnit.MILLISECONDS);

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

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

        @Override
        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);
    }
}


Facebook面试题:Task Schedule

第一题是Task Schedule, 地里有面经。大致意思是每种task都有冷却时间,比如task1执行后,要经过interval时间后才能再次执行,求总共所需时间。. 1point3acres.co...
  • DieHorseSpecial
  • DieHorseSpecial
  • 2016年10月17日 04:23
  • 1377

Win7 TaskSchedule(任务计划程序库…

TaskSchedule经常会在服务器上用到,用于自动去执行一些程序或脚本 TaskSchedule可以通过控制面板-->系统与安全-->管理工具-->任务计划程序打开 也可以使用命令tasksch...
  • dfy11011
  • dfy11011
  • 2015年04月17日 20:06
  • 278

Windows的定时任务(Schedule Task)设置

一、设置 1 点击“开始” 2 点击“控制面板” 3 双击“任务计划” 4 双击“添加任务计划” 5 到了“任务计划向导”界面,点击“下一步” 6 点击“浏览”选择...
  • woshixuye
  • woshixuye
  • 2013年07月16日 10:26
  • 16295

schedule(TimerTask task, long delay, long period) 抛 IllegalArgumentException

看图 - -    源码中注释和代码有差异 = = period
  • zgf1991
  • zgf1991
  • 2012年12月04日 15:14
  • 890

timer.schedule —— timer定时器的用法

java.util.Timer定时器,实际上是个线程,定时调度所拥有的TimerTasks。 一个TimerTask实际上就是一个拥有run方法的类,需要定时执行的代码放到run方法体内,Timer...
  • lintianlin
  • lintianlin
  • 2014年10月28日 15:28
  • 11421

hdu Task schedule

Problem Description 有一台机器,并且给你这台机器的工作表,工作表上有n个任务,机器在ti时间执行第i个任务,1秒即可完成1个任务。 有m个询问,每个询问有一个数字q,表示如果在...
  • qq_20200047
  • qq_20200047
  • 2017年03月24日 13:08
  • 109

Timer.schedule (TimerTask task, long delay, long period) 参数说明

Timer是一种定时器工具,用来在一个后台线程计划执行指定任务。它可以计划执行一个任务一次或反复多次。 TimerTask一个抽象类,它的子类代表一个可以被Timer计划的任务。 schedu...
  • u012100917
  • u012100917
  • 2014年02月20日 09:33
  • 2204

java.util.Timer的schedule(TimerTask task,Date firstTime,long peroid)

public void schedule(TimerTask task, Date firstTime, long ...
  • zfy920123
  • zfy920123
  • 2015年04月22日 08:43
  • 865

HDU3572Task Schedule(最大流 ISAP比较快)建图方法不错

Task Schedule Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) ...
  • u010372095
  • u010372095
  • 2015年06月11日 21:39
  • 945

Spring3 Schedule Task之注解实现 (两次起动Schedule Task 的解决方案)

Spring3 Schedule Task之注解实现 (两次起步Schedule Task 的解决方案) Spring3 Schedule Task之注解实现 (两次启动Schedule Task ...
  • w2222288
  • w2222288
  • 2015年12月14日 14:50
  • 4510
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:How to schedule task daily + onStart() in Play 2.0.4?
举报原因:
原因补充:

(最多只允许输入30个字)