Spring 定時任務的幾種實現

前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。

近日項目開發中需要執行一些定時任務,比如需要在每天凌晨時候,分析一次前一天的日志信息,借此機會整理了一下定時任務的幾種實現方式,由于項目采用spring框架,所以我都將結合spring框架來介紹。

一.分類

  • 從實現的技術上來分類,目前主要有三種技術(或者說有三種產品):

  1. Java自帶的java.util.Timer類,這個類允許你調度一個java.util.TimerTask任務。使用這種方式可以讓你的程序按照某一個頻度執行,但不能在指定時間運行。一般用的較少,這篇文章將不做詳細介紹。
  2. 使用Quartz,這是一個功能比較強大的的調度器,可以讓你的程序在指定時間執行,也可以按照某一個頻度執行,配置起來稍顯復雜,稍后會詳細介紹。
  3. Spring3.0以后自帶的task,可以將它看成一個輕量級的Quartz,而且使用起來比Quartz簡單許多,稍后會介紹。
  • 從作業類的繼承方式來講,可以分為兩類:

  1. 作業類需要繼承自特定的作業類基類,如Quartz中需要繼承自org.springframework.scheduling.quartz.QuartzJobBean;java.util.Timer中需要繼承自java.util.TimerTask。
  2. 作業類即普通的java類,不需要繼承自任何基類。

注:個人推薦使用第二種方式,因為這樣所以的類都是普通類,不需要事先區別對待。

?

  • 從任務調度的觸發時機來分,這里主要是針對作業使用的觸發器,主要有以下兩種:

  1. 每隔指定時間則觸發一次,在Quartz中對應的觸發器為:org.springframework.scheduling.quartz.SimpleTriggerBean
  2. 每到指定時間則觸發一次,在Quartz中對應的調度器為:org.springframework.scheduling.quartz.CronTriggerBean

注:并非每種任務都可以使用這兩種觸發器,如java.util.TimerTask任務就只能使用第一種。Quartz和spring task都可以支持這兩種觸發條件。

?

二.用法說明

詳細介紹每種任務調度工具的使用方式,包括Quartz和spring task兩種。

Quartz

第一種,作業類繼承自特定的基類:org.springframework.scheduling.quartz.QuartzJobBean。

第一步:定義作業類

Java代碼??

  1. import?org.quartz.JobExecutionContext;??
  2. import?org.quartz.JobExecutionException;??
  3. import?org.springframework.scheduling.quartz.QuartzJobBean;??
  4. public?class?Job1?extends?QuartzJobBean?{??
  5. ??
  6. private?int?timeout;??
  7. private?static?int?i?=?0;??
  8. //調度工廠實例化后,經過timeout時間開始執行調度??
  9. public?void?setTimeout(int?timeout)?{??
  10. this.timeout?=?timeout;??
  11. }??
  12. ??
  13. /**?
  14. *?要調度的具體任務?
  15. */??
  16. @Override??
  17. protected?void?executeInternal(JobExecutionContext?context)??
  18. throws?JobExecutionException?{??
  19. ??System.out.println("定時任務執行中…");??
  20. }??
  21. }??

?第二步:spring配置文件中配置作業類JobDetailBean

Xml代碼??

  1. <bean?name="job1"?class="org.springframework.scheduling.quartz.JobDetailBean">??
  2. <property?name="jobClass"?value="com.gy.Job1"?/>??
  3. <property?name="jobDataAsMap">??
  4. <map>??
  5. <entry?key="timeout"?value="0"?/>??
  6. </map>??
  7. </property>??
  8. </bean>??

?說明:org.springframework.scheduling.quartz.JobDetailBean有兩個屬性,jobClass屬性即我們在java代碼中定義的任務類,jobDataAsMap屬性即該任務類中需要注入的屬性值。

第三步:配置作業調度的觸發方式(觸發器)

Quartz的作業觸發器有兩種,分別是

org.springframework.scheduling.quartz.SimpleTriggerBean

org.springframework.scheduling.quartz.CronTriggerBean

第一種SimpleTriggerBean,只支持按照一定頻度調用任務,如每隔30分鐘運行一次。

配置方式如下:

Xml代碼??

  1. <bean?id="simpleTrigger"?class="org.springframework.scheduling.quartz.SimpleTriggerBean">??
  2. <property?name="jobDetail"?ref="job1"?/>??
  3. <property?name="startDelay"?value="0"?/><!--?調度工廠實例化后,經過0秒開始執行調度?-->??
  4. <property?name="repeatInterval"?value="2000"?/><!--?每2秒調度一次?-->??
  5. </bean>??

第二種CronTriggerBean,支持到指定時間運行一次,如每天12:00運行一次等。

配置方式如下:

Xml代碼??

  1. <bean?id="cronTrigger"?class="org.springframework.scheduling.quartz.CronTriggerBean">??
  2. <property?name="jobDetail"?ref="job1"?/>??
  3. <!—每天12:00運行一次?-->??
  4. <property?name="cronExpression"?value="0?0?12?*?*??"?/>??
  5. </bean>??

?關于cronExpression表達式的語法參見附錄。

第四步:配置調度工廠?

Xml代碼??

  1. <bean?class="org.springframework.scheduling.quartz.SchedulerFactoryBean">??
  2. <property?name="triggers">??
  3. <list>??
  4. <ref?bean="cronTrigger"?/>??
  5. </list>??
  6. </property>??
  7. </bean>??

?說明:該參數指定的就是之前配置的觸發器的名字。

第五步:啟動你的應用即可,即將工程部署至tomcat或其他容器。

?

第二種,作業類不繼承特定基類。

Spring能夠支持這種方式,歸功于兩個類:

org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean

org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean

這兩個類分別對應spring支持的兩種實現任務調度的方式,即前文提到到java自帶的timer task方式和Quartz方式。這里我只寫MethodInvokingJobDetailFactoryBean的用法,使用該類的好處是,我們的任務類不再需要繼承自任何類,而是普通的pojo。

第一步:編寫任務類

Java代碼??

  1. public?class?Job2?{??
  2. public?void?doJob2()?{??
  3. System.out.println("不繼承QuartzJobBean方式-調度進行中...");??
  4. }??
  5. }??

?可以看出,這就是一個普通的類,并且有一個方法。

第二步:配置作業類

Xml代碼??

  1. <bean?id="job2"??
  2. class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">??
  3. <property?name="targetObject">??
  4. <bean?class="com.gy.Job2"?/>??
  5. </property>??
  6. <property?name="targetMethod"?value="doJob2"?/>??
  7. <property?name="concurrent"?value="false"?/><!--?作業不并發調度?-->??
  8. </bean>??

?說明:這一步是關鍵步驟,聲明一個MethodInvokingJobDetailFactoryBean,有兩個關鍵屬性:targetObject指定任務類,targetMethod指定運行的方法。往下的步驟就與方法一相同了,為了完整,同樣貼出。

第三步:配置作業調度的觸發方式(觸發器)

Quartz的作業觸發器有兩種,分別是

org.springframework.scheduling.quartz.SimpleTriggerBean

org.springframework.scheduling.quartz.CronTriggerBean

第一種SimpleTriggerBean,只支持按照一定頻度調用任務,如每隔30分鐘運行一次。

配置方式如下:

Xml代碼??

  1. <bean?id="simpleTrigger"?class="org.springframework.scheduling.quartz.SimpleTriggerBean">??
  2. <property?name="jobDetail"?ref="job2"?/>??
  3. <property?name="startDelay"?value="0"?/><!--?調度工廠實例化后,經過0秒開始執行調度?-->??
  4. <property?name="repeatInterval"?value="2000"?/><!--?每2秒調度一次?-->??
  5. </bean>??

?第二種CronTriggerBean,支持到指定時間運行一次,如每天12:00運行一次等。

配置方式如下:

Xml代碼??

  1. <bean?id="cronTrigger"?class="org.springframework.scheduling.quartz.CronTriggerBean">??
  2. <property?name="jobDetail"?ref="job2"?/>??
  3. <!—每天12:00運行一次?-->??
  4. <property?name="cronExpression"?value="0?0?12?*?*??"?/>??
  5. </bean>??

以上兩種調度方式根據實際情況,任選一種即可。

第四步:配置調度工廠?

Xml代碼??

  1. <bean?class="org.springframework.scheduling.quartz.SchedulerFactoryBean">??
  2. <property?name="triggers">??
  3. <list>??
  4. <ref?bean="cronTrigger"?/>??
  5. </list>??
  6. </property>??
  7. </bean>??

說明:該參數指定的就是之前配置的觸發器的名字。

第五步:啟動你的應用即可,即將工程部署至tomcat或其他容器。

?

到此,spring中Quartz的基本配置就介紹完了,當然了,使用之前,要導入相應的spring的包與Quartz的包,這些就不消多說了。

其實可以看出Quartz的配置看上去還是挺復雜的,沒有辦法,因為Quartz其實是個重量級的工具,如果我們只是想簡單的執行幾個簡單的定時任務,有沒有更簡單的工具,有!

請看我第下文Spring task的介紹。

?

Spring-Task

上節介紹了在Spring 中使用Quartz,本文介紹Spring3.0以后自主開發的定時任務工具,spring task,可以將它比作一個輕量級的Quartz,而且使用起來很簡單,除spring相關的包外不需要額外的包,而且支持注解和配置文件兩種

形式,下面將分別介紹這兩種方式。

第一種:配置文件方式

第一步:編寫作業類

即普通的pojo,如下:

Java代碼??

  1. import?org.springframework.stereotype.Service;??
  2. @Service??
  3. public?class?TaskJob?{??
  4. ??????
  5. ????public?void?job1()?{??
  6. ????????System.out.println(“任務進行中。。。”);??
  7. ????}??
  8. }??

?第二步:在spring配置文件頭中添加命名空間及描述

Xml代碼??

  1. <beans?xmlns="http://www.springframework.org/schema/beans"??
  2. ????xmlns:task="http://www.springframework.org/schema/task"???
  3. ????。。。。。。??
  4. ????xsi:schemaLocation="http://www.springframework.org/schema/task?http://www.springframework.org/schema/task/spring-task-3.0.xsd">??

?第三步:spring配置文件中設置具體的任務

Xml代碼??

  1. ?<task:scheduled-tasks>???
  2. ????????<task:scheduled?ref="taskJob"?method="job1"?cron="0?*?*?*?*??"/>???
  3. </task:scheduled-tasks>??
  4. ??
  5. <context:component-scan?base-package="?com.gy.mytask?"?/>??

說明:ref參數指定的即任務類,method指定的即需要運行的方法,cron及cronExpression表達式,具體寫法這里不介紹了,詳情見上篇文章附錄。

<context:component-scan base-package="com.gy.mytask" />這個配置不消多說了,spring掃描注解用的。

到這里配置就完成了,是不是很簡單。

第二種:使用注解形式

也許我們不想每寫一個任務類還要在xml文件中配置下,我們可以使用注解@Scheduled,我們看看源文件中該注解的定義:

Java代碼??

  1. @Target({java.lang.annotation.ElementType.METHOD,?java.lang.annotation.ElementType.ANNOTATION_TYPE})??
  2. @Retention(RetentionPolicy.RUNTIME)??
  3. @Documented??
  4. public?@interface?Scheduled??
  5. {??
  6. ??public?abstract?String?cron();??
  7. ??
  8. ??public?abstract?long?fixedDelay();??
  9. ??
  10. ??public?abstract?long?fixedRate();??
  11. }??

?可以看出該注解有三個方法或者叫參數,分別表示的意思是:

cron:指定cron表達式

fixedDelay:官方文檔解釋:An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds.即表示從上一個任務完成開始到下一個任務開始的間隔,單位是毫秒。

fixedRate:官方文檔解釋:An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds.即從上一個任務開始到下一個任務開始的間隔,單位是毫秒。

?

下面我來配置一下。

第一步:編寫pojo

Java代碼??

  1. import?org.springframework.scheduling.annotation.Scheduled;????
  2. import?org.springframework.stereotype.Component;??
  3. ??
  4. @Component(“taskJob”)??
  5. public?class?TaskJob?{??
  6. ????@Scheduled(cron?=?"0?0?3?*?*??")??
  7. ????public?void?job1()?{??
  8. ????????System.out.println(“任務進行中。。。”);??
  9. ????}??
  10. }??

?第二步:添加task相關的配置:

Xml代碼??

  1. <beans?xmlns="http://www.springframework.org/schema/beans"??
  2. ????xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"?xmlns:aop="http://www.springframework.org/schema/aop"??
  3. ????xmlns:context="http://www.springframework.org/schema/context"??
  4. ????xmlns:tx="http://www.springframework.org/schema/tx"??
  5. ????xmlns:task="http://www.springframework.org/schema/task"??
  6. ????xsi:schemaLocation="??
  7. ????????http://www.springframework.org/schema/beans?http://www.springframework.org/schema/beans/spring-beans-3.0.xsd??
  8. ????????http://www.springframework.org/schema/aop?http://www.springframework.org/schema/aop/spring-aop-3.0.xsd??
  9. ????????http://www.springframework.org/schema/context???
  10. http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd??
  11. ????????http://www.springframework.org/schema/tx?http://www.springframework.org/schema/tx/spring-tx-3.0.xsd??
  12. ????????http://www.springframework.org/schema/task?http://www.springframework.org/schema/task/spring-task-3.0.xsd"??
  13. ????default-lazy-init="false">??
  14. ??
  15. ??
  16. ????<context:annotation-config?/>??
  17. ????<!—spring掃描注解的配置???-->??
  18. ????<context:component-scan?base-package="com.gy.mytask"?/>??
  19. ??????
  20. <!—開啟這個配置,spring才能識別@Scheduled注解???-->??
  21. ????<task:annotation-driven?scheduler="qbScheduler"?mode="proxy"/>??
  22. ????<task:scheduler?id="qbScheduler"?pool-size="10"/>??

說明:理論上只需要加上<task:annotation-driven />這句配置就可以了,這些參數都不是必須的。

?

?Ok配置完畢,當然spring task還有很多參數,我就不一一解釋了,具體參考xsd文檔http://www.springframework.org/schema/task/spring-task-3.0.xsd。

附錄:

cronExpression的配置說明,具體使用以及參數請百度google

字段 ? 允許值 ? 允許的特殊字符

秒 ? ?0-59 ? ?, - * /

分 ? ?0-59 ? ?, - * /

小時 ? ?0-23 ? ?, - * /

日期 ? ?1-31 ? ?, - * ? / L W C

月份 ? ?1-12 或者 JAN-DEC ? ?, - * /

星期 ? ?1-7 或者 SUN-SAT ? ?, - * ? / L C #

年(可選) ? ?留空, 1970-2099 ? ?, - * /?

- 區間 ?

* 通配符 ?

? 你不想設置那個字段

下面只例出幾個式子

?

?

?CRON表達式詳解 見另一頁博客:http://blog.csdn.net/jiangyu1013/article/details/54405859

CRON表達式 ? ?含義?

"0 0 12 * * ?" ? ?每天中午十二點觸發?

"0 15 10 ? * *" ? ?每天早上10:15觸發?

"0 15 10 * * ?" ? ?每天早上10:15觸發?

"0 15 10 * * ? *" ? ?每天早上10:15觸發?

"0 15 10 * * ? 2005" ? ?2005年的每天早上10:15觸發?

"0 * 14 * * ?" ? ?每天從下午2點開始到2點59分每分鐘一次觸發?

"0 0/5 14 * * ?" ? ?每天從下午2點開始到2:55分結束每5分鐘一次觸發?

"0 0/5 14,18 * * ?" ? ?每天的下午2點至2:55和6點至6點55分兩個時間段內每5分鐘一次觸發?

"0 0-5 14 * * ?" ? ?每天14:00至14:05每分鐘一次觸發?

"0 10,44 14 ? 3 WED" ? ?三月的每周三的14:10和14:44觸發?

"0 15 10 ? * MON-FRI" ? ?每個周一、周二、周三、周四、周五的10:15觸發?

?

轉自:http://gong1208.iteye.com/blog/1773177

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/451963.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/451963.shtml
英文地址,請注明出處:http://en.pswp.cn/news/451963.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

trie樹(字典樹)

trie樹學習 學習trie樹 轉載于:https://www.cnblogs.com/cjoierljl/p/9317023.html

Vue 教程第四篇—— Vue 實例化時基本屬性

實例元素 el 實例元素指的是 Vue 實例化時編譯的容器元素&#xff0c;或者說是 Vue 作用的元素容器 <div id"app"></div> var vm new Vue({el: #app}) 也可以為實例元素指定其它選擇器 <div class"app"></div> var vm new Vue({…

Ubuntu將在明年推出平板及手機系統

4月26日下午消息&#xff0c;知名Linux廠商Canonical今天正式發布Ubuntu 12.04版開源操作系統。Ubuntu中國首席代表于立強透露&#xff0c;針對平板電腦的Ubuntu操作系統將在明年推出。 Ubuntu 12.04版開源操作系統發布 Ubuntu操作系統是一款開源操作系統&#xff0c;主要與OE…

scrapy框架異常--no more duplicates will be shown (see DUPEFILTER_DEBUG to show all duplicates)

解決方法&#xff1a; https://blog.csdn.net/qq_40176258/article/details/86527568 https://blog.csdn.net/weixin_39946931/article/details/88390797 謝謝博主分享&#xff01;

【BZOJ3590】[Snoi2013]Quare 狀壓DP

題解&#xff1a; 一道比較水的題 但這個測試數據極弱我也不知道我的代碼正確性是不是有保證 構成一個邊雙聯通 可以由兩個有一個公共點的邊雙聯通或者一個邊雙加一條鏈構成 所以我們需要要預處理出所有環 令f[i][j][k]表示起點為i&#xff0c;終點為j&#xff0c;經過點的狀態…

java swing簡介

UI 組件簡介 在開始學習 Swing 之前&#xff0c;必須回答針對真正初學者的一個問題&#xff1a;什么是 UI&#xff1f;初學者的答案是“用戶界面”。但是因為本教程的目標是要保證您不再只是個初學者&#xff0c;所以我們需要比這個定義更高級的定義。 所以&#xff0c;我再次…

定時任務 cron 表達式詳解

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 &#xff08;Spring定時任務的幾種實現&#xff1a;見博客另一頁&#xff1a;http://blog.csdn.net/jiangyu1013/article/details/54405…

Android Studio 超級簡單的打包生成apk

為什么要打包&#xff1a; apk文件就是一個包&#xff0c;打包就是要生成apk文件&#xff0c;有了apk別人才能安裝使用。打包分debug版和release包&#xff0c;通常所說的打包指生成release版的apk&#xff0c;release版的apk會比debug版的小&#xff0c;release版的還會進行混…

推薦16款最棒的Visual Studio插件

Visual Studio是微軟公司推出的開發環境&#xff0c;Visual Studio可以用來創建Windows平臺下的Windows應用程序和網絡應用程序&#xff0c;也可以用來創建網絡服務、智能設備應用程序和Office插件。 本文介紹16款最棒的Visual Studio擴展&#xff1a; 1. DevColor Extension…

網絡爬蟲--22.【CrawlSpider實戰】實現微信小程序社區爬蟲

文章目錄一. CrawlSpider二. CrawlSpider案例1. 目錄結構2. wxapp_spider.py3. items.py4. pipelines.py5. settings.py6. start.py三. 重點總結一. CrawlSpider 現實情況下&#xff0c;我們需要對滿足某個特定條件的url進行爬取&#xff0c;這時候就可以通過CrawlSpider完成。…

可以生成自動文檔的注釋

使用/**和*/可以用來自動的生成文檔。 這種注釋以/**開頭&#xff0c;以*/結尾

怎么安裝Scrapy框架以及安裝時出現的一系列錯誤(win7 64位 python3 pycharm)

因為要學習爬蟲&#xff0c;就打算安裝Scrapy框架&#xff0c;以下是我安裝該模塊的步驟&#xff0c;適合于剛入門的小白&#xff1a; 一、打開pycharm&#xff0c;依次點擊File---->setting---->Project----->Project Interpreter&#xff0c;打開后&#xff0c;可以…

illegal to have multiple occurrences of contentType with different values 解決

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 在網上查到說是&#xff1a;“包含頁面與被包含頁面的page指令里面的contentType不一致&#xff0c;仔細檢查兩個文件第一行的 page....…

xpath-helper: 谷歌瀏覽器安裝xpath helper 插件

1.下載文件xpath-helper.crx xpath鏈接&#xff1a;https://pan.baidu.com/s/1dFgzBSd 密碼&#xff1a;zwvb&#xff0c;感謝這位網友&#xff0c;我從這拿到了 2.在Google瀏覽器里邊找到這個“擴展程序”選項菜單即可。 3.然后就會進入到擴展插件的界面了,把下載好的離線插件…

網絡爬蟲--23.動態網頁數據抓取

文章目錄一. Ajax二. 獲取Ajax數據的方式三. seleniumchromedriver獲取動態數據四. selenium基本操作一. Ajax 二. 獲取Ajax數據的方式 三. seleniumchromedriver獲取動態數據 selenium文檔&#xff1a;https://selenium-python.readthedocs.io/installation.html 四. sele…

視音頻編解碼技術及其實現

核心提示&#xff1a;一、視音頻編碼國際標準化組織及其壓縮標準介紹 國際上有兩個負責視音頻編碼的標準化組織&#xff0c;一個是VCEG&#xff08;VideocodeExpertGroup&#xff09;&#xff0c;是國際電信聯合會下的視頻編碼專家組&#xff0c;一個是MPEG&#xff08;MotionP…

什么是NaN

NaN&#xff0c;是Not a Number的縮寫。NaN 用于處理計算中出現的錯誤情況&#xff0c;比如 0.0 除以 0.0 或者求負數的平方根。由上面的表中可以看出&#xff0c;對于單精度浮點數&#xff0c;NaN 表示為指數為 emax 1 128&#xff08;指數域全為 1&#xff09;&#xff0c;…

排序系列【比較排序系列之】直接插入排序

最近在和小伙伴們一起研究排序&#xff0c;排序分好多總&#xff0c;后期會做整體總結&#xff0c;本篇則主要對插入排序進行一個整理。 插入排序&#xff08;insert sorting&#xff09;的算法思想十分簡單&#xff0c;就是對待排序的記錄逐個進行處理&#xff0c;每個新紀錄…

Mysql 無法插入中文,中文亂碼解決

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 在計算機中搜索 my.ini文件 找到后打開 &#xff0c;并找到這2行作 如下設置 &#xff1a; default-character-setutf8character-se…