Sunday, May 18, 2014

How to schedule Cron jobs in Play 2 ?

http://brainstep.blogspot.com/2013/10/scheduling-jobs-in-play-2.html
http://stackoverflow.com/questions/23198633/scheduled-job-on-play-using-akka

Place the following in the onStart method of the Global.java file we just created.
FiniteDuration delay = FiniteDuration.create(0, TimeUnit.SECONDS); FiniteDuration frequency = FiniteDuration.create(5, TimeUnit.SECONDS); Runnable showTime = new Runnable() {
            @Override
            public void run() {
                System.out.println("Time is now: " + new Date());
            }
        };

Akka.system().scheduler().schedule(delay, frequency, showTime, Akka.system().dispatcher());
The above simply allows us to log the current time to the console ever 5 seconds. 


Now that we've covered the basics, let's move on to creating a useful schedule. The schedule that we'll create will run a task at 4PM every day.
 
Long delayInSeconds;

Calendar c = Calendar.getInstance();  

c.set(Calendar.HOUR_OF_DAY, 16);  
c.set(Calendar.MINUTE, 0); 
c.set(Calendar.SECOND, 0);
Date plannedStart = c.getTime();  
Date now = new Date();  
Date nextRun;  
if(now.after(plannedStart)) {
   c.add(Calendar.DAY_OF_WEEK, 1);
   nextRun = c.getTime();
 

} else {
   nextRun = c.getTime();
}
 delayInSeconds = (nextRun.getTime() - now.getTime()) / 1000; //To convert milliseconds to seconds.

FiniteDuration delay = FiniteDuration.create(delayInSeconds, TimeUnit.SECONDS);  

FiniteDuration frequency = FiniteDuration.create(1, TimeUnit.DAYS);  
Runnable showTime = new Runnable() {
            @Override
            public void run() {
                System.out.println("Time is now: " + new Date());
            }
        };

Akka.system().scheduler().schedule(delay, frequency, showTime, Akka.system().dispatcher());

Now every day at 4PM your application will remind you of the time. Awesome.


1 comment:

Unknown said...

David this actually goes against what the Akka Scheduler was meant to do ( What's wrong with Akka's existing Scheduler? As Viktor Klang points out, 'Perhaps the name "Scheduler" was unfortunate, "Deferer" is probably more indicative of what it does.'.

Please take a look at this:

https://github.com/typesafehub/akka-quartz-scheduler/

Hope this helps.