Skip to content

Instantly share code, notes, and snippets.

@fengxuan
Last active December 19, 2015 01:19
Show Gist options
  • Save fengxuan/5875102 to your computer and use it in GitHub Desktop.
Save fengxuan/5875102 to your computer and use it in GitHub Desktop.
play 2.0 akka schedule just like play1.0 job
import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import play.Logger;
import play.libs.Akka;
import play.libs.Time.CronExpression;
import scala.concurrent.duration.FiniteDuration;
import akka.actor.Cancellable;
/**
* job base class
* @author feng
*
*/
public abstract class BaseJob extends Thread implements Cancellable{
private String cornFinal;
private boolean isCanceled;
public BaseJob(String corn) {
this.cornFinal = corn;
}
public abstract void doJob();
@Override
public void run() {
Logger.debug("Ruuning scheduler :" + cornFinal);
try {
// Do your tasks here
doJob();
} catch (Exception e) {
Logger.error("doJob error", e);
}
}
/**
* schedule every 1 day
*/
public Cancellable scheduleInterval() {
FiniteDuration d = getScheduleTime();
FiniteDuration oneDay = FiniteDuration.create(1, TimeUnit.DAYS);
return Akka.system().scheduler()
.schedule(d, oneDay, this, Akka.system().dispatcher());
}
/**
* schedule once
*/
public Cancellable scheduleOnce() {
FiniteDuration d = getScheduleTime();
return Akka.system().scheduler()
.scheduleOnce(d, this, Akka.system().dispatcher());
}
public FiniteDuration getScheduleTime() {
FiniteDuration d = null;
try {
CronExpression e = new CronExpression(cornFinal);
Date nextValidTimeAfter = e.getNextValidTimeAfter(new Date());
d = FiniteDuration.create(
nextValidTimeAfter.getTime() - System.currentTimeMillis(),
TimeUnit.MILLISECONDS);
Logger.debug("Scheduling to run at " + nextValidTimeAfter);
} catch (ParseException e) {
e.printStackTrace();
}
return d;
}
@Override
public void cancel() {
isCanceled = true;
}
@Override
public boolean isCancelled() {
return isCanceled;
}
}
public class Global extends GlobalSettings
{
private List<Cancellable> jobs = new ArrayList<Cancellable>(2);
@Override
public void onStart(Application app)
{
injector = Guice.createInjector(new Our108GuiceModule());
Logger.info("Global.onStart and usedAuth:" + !Constants.IS_TEST);
super.onStart(app);
String corn = "0 12 22 * * ?";
jobs.add(new UserRankJob(corn).scheduleInterval());
}
@Override
public void onStop(Application app)
{
Logger.info("Global.onStop...");
// cancel scheduled jobs
Logger.info("Jobs Cancellable.");
for (Cancellable sch : jobs) {
sch.cancel();
}
super.onStop(app);
}
}
public class UserRankJob extends BaseJob {
public UserRankJob(String corn) {
super(corn);
}
@Override
public void doJob() {
Logger.debug("UserRankJob do something start.");
Logger.debug("UserRankJob do something end.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment