什么是Quartz?
Quartz是一个强大的企业级任务调度框架。它允许开发人员灵活地定义触发器的调度时间表,并可对触发器和任务进行关联映射。此外,Quartz提供了调度运行环境的持久化机制,可以保存并会发调度现场,即使系统因故障关闭,任务调度现场数据并不会丢失。Spring中继承并简化了Quartz。
如何使用Quartz?
对于Quartz,我们使用的时候主要是注重两个方面,一个是定时任务的业务,另一个就是Cron表达式。
1>Quartz存在两种方式来定义定时执行任务,一种是使用QuartJobBean和JobDetailBean;另一种是使用MethodInvokingJobDetailFactoryBean。
2>Cron表达式包括下面7个字段并区别顺序:秒0-59,分0-59,小时0-23,月内日期1-31,月1-12或者JAN-DEC,周内日期1-7或者SUN-SAT,年(可选字段)留空或者1970-2099并且通过特殊字符表示特殊意义,具体为下:
例子:
"0 0 08 * * ?" 每天上午8点触发
"0 15 10 ? * *" 每天上午10:15触发
"0 15 10 * * ?" 每天上午10:15触发
"0 15 10 ? * 6L 2009-2019" 2009年至2019年的每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发
【示例】
我们使用Spring定时服务Quartz来实现一个每5秒打印一次当前时间的小例子。
1:定义接口IPrintInfoService类
package demoinfo.spring.quartz;
public interface IPrintInfoService {
public void print();
}2:实现接口类PrintInfoServiceImpl
package demoinfo.spring.quartz;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import demoinfo.spring.quartz.IPrintInfoService;
public class PrintInfoServiceImpl implements IPrintInfoService{
public void print() {
Calendar now = Calendar.getInstance();
System.out.println("现在是北京时间:" + this.format(now.getTime()));
}
public String format(Date date){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
}3:基于QuartzJobBean的实现类PrintInfoJob
package demoinfo.spring.quartz;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import demoinfo.spring.quartz.IPrintInfoService;
public class PrintInfoJob extends QuartzJobBean{
private IPrintInfoService prinfInfoService = null;
public IPrintInfoService getPrinfInfoService() {
return prinfInfoService;
}
public void setPrinfInfoService(IPrintInfoService prinfInfoService) {
this.prinfInfoService = prinfInfoService;
}
@Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
this.prinfInfoService.print();
}
}4:Spring配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>6000 6000 00,05,10,15,20,25,30,35,40,45,50,55 * * * * ?
5:测试用例类SpringQuartzDemo
package demoinfo.spring.quartz;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringQuartzDemo {
public static void main(String[] args) {
System.out.println("测试开始......");
new ClassPathXmlApplicationContext(
"classpath:demoinfo/spring/quartz/applicationContext.xml");
System.out.println("测试结束......");
}
}运行测试用例,可以看到控制台每过5秒钟就打印一次时间信息。