Play框架提供了定时执行任务的功能模块,也就是Job。大家可以用来做一些定时的任务,如数据汇总,定时同步等。play使用了Quartz项目。可以轻松地定制调度任务的时间。Play框架还预置了几种调度方式,如项目启动调度,启动异步调动,每多少时间调度,和通用的Quartz调度设置。 首先我们看看启动调度,启动调度是同步于项目启动:
package job;
import play.jobs.Job;
import play.jobs.OnApplicationStart;
@OnApplicationStart
public class JobOnStart extends Job{
@Override
public void doJob() throws Exception {
super.doJob();
System.out.println("Hello Job!");
}
}
还有启动异步调度:
package job;
import play.jobs.Job;
import play.jobs.OnApplicationStart;
@OnApplicationStart(async = true)
public class JobOnStartAsync extends Job{
@Override
public void doJob() throws Exception {
super.doJob();
System.out.println("Hello Job, this is a async!");
}
}
然后还有每多少时间调度:
package job;
import play.jobs.Every;
import play.jobs.Job;
@Every("1min")
public class JobOnSomeTime extends Job{
@Override
public void doJob() throws Exception {
System.out.println("Hello Clock! Minute Over!");
}
}
还有通用的Quartz调度:
package job;
import play.jobs.Job;
import play.jobs.On;
@On(value = "0 28 11 ? * *")
public class JobOnCommon extends Job{
public void doJob() throws Exception {
System.out.println("Hello 11:28!");
}
}
控制台的打印:
11:26:17,730 INFO ~ Application 'Proto' is now started !
Hello Job!
Hello Job, this is a async!
11:26:17,903 INFO ~ Listening for HTTP on port 9000 ...
Hello Clock! Minute Over!
Hello 11:28!
Hello Clock! Minute Over!
Hello Clock! Minute Over!
Hello Clock! Minute Over!
Quartz 是个开放源码项目,提供了丰富的作业调度集。上面表达式中@on注解对应的字段是: Seconds Minutes Hours DayofMonth Month DayofWeek Year(year为可选字段,一般可以省略) 如:0 28 11 ? * * :每天11点28分 24 30 1 ? * WED : 每周三1点20分24秒
更详细的介绍可以查考官网: http://quartz-scheduler.org/
IBM的developerworks中也有文章: http://www.ibm.com/developerworks/cn/java/j-quartz/index.html
百度文库中的介绍: http://wenku.baidu.com/view/0e3b19e6f8c75fbfc77db22a.html
来源:oschina
链接:https://my.oschina.net/u/1386633/blog/498132