官方的Quartz会提供例子的,例子看个前三四个感觉就够用了,主要就是起Timer的作用,但是比timer稳定,而且功能更全。
UpdateClientTimer.task(ClearJob.class, GlobalVars.CLEAR_MAP_TIMER);
一个反射的参数和一个Quartz表达式,这个表达式功能很强大
public static void task(Class cls, String expression) throws SchedulerException {
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
// current time
long ctime = System.currentTimeMillis();
JobDetail jobDetail = new JobDetail("detail", "group", cls);
// Initiate CronTrigger with its name and group name
CronTrigger cronTrigger = new CronTrigger("cronTrigger", "group");
try {
// setup CronExpression
CronExpression cexp = new CronExpression(expression);
//CronExpression cexp = new CronExpression("10 * * * * ?");
// Assign the CronExpression to CronTrigger
cronTrigger.setCronExpression(cexp);
} catch (Exception e) {
e.printStackTrace();
}
// schedule a job with JobDetail and Trigger
scheduler.scheduleJob(jobDetail, cronTrigger);
// start the scheduler
scheduler.start();
}
Quartz开始工作了 ,调度频率得看那个class是怎么写的。
public class ClearJob implements Job {
private static Logger log = Logger.getLogger(ClearJob.class);
@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
log.info("start clear job ");
java.util.Calendar c = java.util.Calendar.getInstance();
int min = c.get(java.util.Calendar.MINUTE);
int second = c.get(java.util.Calendar.SECOND);
try {
if(min % 15 == 0 &&second == 0){
}
if(second % 10 == 0 ){
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
我设置的调度器是10秒调度一次(具体频率由expression决定)
然后在里面有两个动作,一个是10秒触发,一个是15分钟触发。