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觸發
【示例】
我們使用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'?><beans xmlns='http://www.springframework.org/schema/beans' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:context='http://www.springframework.org/schema/context' xmlns:tx='http://www.springframework.org/schema/tx' xsi:schemaLocation='http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd'> <bean /> <!-- 配置一個Job --> <bean class='org.springframework.scheduling.quartz.JobDetailBean'> <property name='jobClass' value='demoinfo.spring.quartz.PrintInfoJob' /> <property name='jobDataAsMap'> <map><entry key='prinfInfoService' value-ref='printInfoService'></entry> </map> </property> </bean> <!-- 簡單的觸發器 --> <bean class='org.springframework.scheduling.quartz.SimpleTriggerBean'> <property name='jobDetail'> <ref bean='printInfoJob' /> </property> <property name='startDelay'> <value>6000</value> </property> <property name='repeatInterval'> <value>6000</value> </property> </bean> <!--復雜的觸發器 --> <bean class='org.springframework.scheduling.quartz.CronTriggerBean'> <property name='jobDetail'> <ref bean='printInfoJob' /> </property> <property name='cronExpression'> <value>00,05,10,15,20,25,30,35,40,45,50,55 * * * * ?</value> </property> </bean> <!-- spring觸發工廠 --> <bean class='org.springframework.scheduling.quartz.SchedulerFactoryBean'> <property name='triggers'> <list><ref bean='complexPrintInfoTrigger' /> </list> </property> </bean></beans>
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秒鐘就打印一次時間信息。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. React+umi+typeScript創建項目的過程2. ASP調用WebService轉化成JSON數據,附json.min.asp3. php測試程序運行速度和頁面執行速度的代碼4. php網絡安全中命令執行漏洞的產生及本質探究5. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執行過程解析6. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁7. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析8. ASP中常用的22個FSO文件操作函數整理9. SharePoint Server 2019新特性介紹10. 三個不常見的 HTML5 實用新特性簡介
