Spring定時服務QuartZ,Spring服務QuartZ
在JavaEE系統中,我們會經常用到定時任務,比如每天凌晨生成前天報表,每一小時生成匯總數據等等。
我們可以使用java.util.Timer結合java.util.TimerTask來完成這項工作,但時調度控制非常不方便,並且我們需要大量的代碼。
使用Quartz框架無疑是非常好的選擇,並且與Spring可以非常方便的集成。
Spring提供了支持時序調度的整合類。整個構建任務調度服務需要三步:
1)向項目中添加jar包:添加quartz.jar包,將他加到你工程的classpath中去。
2)寫Class文件,在文件中定義你要執行操作的函數你就可以通過配置來達到定時操作了。
3)提供applicationContext.xml Spring配置文件,其中配置你的定時發送操作以及設置定時器的各種屬性(包括運行頻率和初始運行時機)。
小編做了一個每5秒打印一次當前時間的例子,具體請參考源碼,尤其注意配置文件的寫法。(詳見下面“示例”)
【知識准備】
什麼是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並且通過特殊字符表示特殊意義,具體為下:
斜線(/)字符表示增量值。例如,在秒字段中"5/15"代表從第5秒開始,每15秒一次。
問號(?)字符和字母L字符只有在月內日期和周內日期字段中可用。問號表示這個字段不包含具體值。所以,如果指定月內日期,可以在周內日期字段中插入"?",表示周內日期值無關緊要。這裡有個很蛋疼的設定,無關Quartz,而是Spring集成Quartz後,它自己加的一個約束,那就是:日期(1-31)和星期(SUN-SAT)兩者,必須有一個是問號(?),系統在啟動的時候,Spring會檢查表達式,如果不符合它的規則,就會拋異常。所以在使用的時候這個地方一定要注意,而這個在Linux上執行Cron是沒有這個限制的。
字母L字符是last的縮寫。放在月內日期字段中,表示安排在當月最後一天執行。在周內日期字段中,如果"L"單獨存在,就等於"7",否則代表當月內周內日期的最後一個實例。所以"0L"表示安排在當月的最後一個星期日執行。
字母(W)字符把執行安排在最靠近指定值的工作日。把"1W"放在月內日期字段中,表示把執行安排在當月的第一個工作日內。
井號(#)字符為給定月份指定具體的工作日實例。把"MON#2"放在周內日期字段中,表示把任務安排在當月的第二個星期一。
星號(*)字符是通配字符,表示該字段可以接受任何可能的值、表達式例子。
例子:
"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觸發
【資源准備】
1:jar包下載地址:spring jar包 quartz-all-1.6.5.jar包
2.詳細學習參考spring參考手冊spring參考手冊
【示例】
我們使用Spring定時服務Quartz來實現一個每5秒打印一次當前時間的小例子。
1:定義接口IPrintInfoService類

![]()
1 package demoinfo.spring.quartz;
2 public interface IPrintInfoService {
3 public void print();
4 }
View Code
2:實現接口類PrintInfoServiceImpl

![]()
1 package demoinfo.spring.quartz;
2
3 import java.text.SimpleDateFormat;
4 import java.util.Calendar;
5 import java.util.Date;
6
7 import demoinfo.spring.quartz.IPrintInfoService;
8
9 public class PrintInfoServiceImpl implements IPrintInfoService{
10
11 public void print() {
12 Calendar now = Calendar.getInstance();
13 System.out.println("現在是北京時間:" + this.format(now.getTime()));
14 }
15
16 public String format(Date date){
17 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
18 return sdf.format(date);
19 }
20
21 }
View Code
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();
}
}
View Code
4:Spring配置文件applicationContext.xml

![]()
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:context="http://www.springframework.org/schema/context"
5 xmlns:tx="http://www.springframework.org/schema/tx"
6 xsi:schemaLocation="http://www.springframework.org/schema/beans
7 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
8 http://www.springframework.org/schema/context
9 http://www.springframework.org/schema/context/spring-context-2.5.xsd
10 http://www.springframework.org/schema/tx
11 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
12
13
14 <bean id="printInfoService" class="demoinfo.spring.quartz.PrintInfoServiceImpl" />
15 <!-- 配置一個Job -->
16 <bean id="printInfoJob" class="org.springframework.scheduling.quartz.JobDetailBean">
17 <property name="jobClass" value="demoinfo.spring.quartz.PrintInfoJob" />
18 <property name="jobDataAsMap">
19 <map>
20 <entry key="prinfInfoService" value-ref="printInfoService"></entry>
21 </map>
22 </property>
23 </bean>
24
25 <!-- 簡單的觸發器 -->
26 <bean id="simplePrintInfoTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
27 <property name="jobDetail">
28 <ref bean="printInfoJob" />
29 </property>
30 <property name="startDelay">
31 <value>6000</value>
32 </property>
33 <property name="repeatInterval">
34 <value>6000</value>
35 </property>
36 </bean>
37
38 <!--復雜的觸發器 -->
39 <bean id="complexPrintInfoTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
40 <property name="jobDetail">
41 <ref bean="printInfoJob" />
42 </property>
43 <property name="cronExpression">
44 <value>00,05,10,15,20,25,30,35,40,45,50,55 * * * * ?</value>
45 </property>
46 </bean>
47
48 <!-- spring觸發工廠 -->
49 <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
50 <property name="triggers">
51 <list>
52 <ref bean="complexPrintInfoTrigger" />
53 </list>
54 </property>
55 </bean>
56 </beans>
View Code
5:測試用例類SpringQuartzDemo

![]()
1 package demoinfo.spring.quartz;
2
3 import org.springframework.context.support.ClassPathXmlApplicationContext;
4
5 public class SpringQuartzDemo {
6
7 public static void main(String[] args) {
8 System.out.println("測試開始......");
9 new ClassPathXmlApplicationContext(
10 "classpath:demoinfo/spring/quartz/applicationContext.xml");
11 System.out.println("測試結束......");
12 }
13
14 }
View Code
運行測試用例,可以看到控制台每過5秒鐘就打印一次時間信息。