Spring @Scheduled定時任務動態修改cron參數

  Spring框架自3.0版本起,自帶了任務調度功能,好比是一個輕量級的Quartz,而且使用起來也方便、簡單,且不需要依賴其他的JAR包。秉承着Spring的一貫風格,Spring任務調度的實現同時支持註解配置和XML配置兩種方式。

  再來談談變態的項目需求:我們正在做一個智能數字電錶的數據採集項目,項目最終會在多個工業園上線,每個工業園對電錶數據的採集週期可以進行自定義,例如A工業園想每10分鐘採集一次數據,B工業園想每15分鐘採集一次數據。因爲數據採集是個重複的週期性工作,那麼就可以考慮使用Spring框架的定時任務功能了。

  按正常來講,修改定時任務的執行週期還不簡單,把服務停下來,改下任務的cron參數,再重啓服務就搞定了。但有沒有一種可能,在不停服務的情況下,就可以動態的修改任務的cron參數呢?完全是有可能的!

  先來看下Spring常規定時任務的配置,如下:

[html] view plain copy
  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:task="http://www.springframework.org/schema/task"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd   
  8.         http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd   
  9.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">  
  10.       
  11.     <context:component-scan base-package="com.pes_soft.task.demo" />  
  12.       
  13.     <!-- Spring註解方式配置調度任務 -->  
  14.     <task:executor id="executor" pool-size="3"/>  
  15.     <task:scheduler id="scheduler" pool-size="3"/>  
  16.     <task:annotation-driven executor="executor" scheduler="scheduler"/>  
  17. </beans>  

  注意:配置Spring定時任務時,需要在Spring配置文件的xml頭部加入xmlns:task="http://www.springframework.org/schema/task"和xsi:schemaLocation位置中加入http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd

  然後是註解式任務邏輯代碼SpringStaticCronTask.java

[java] view plain copy
  1. package com.pes_soft.task.demo;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5. import org.springframework.context.annotation.Lazy;  
  6. import org.springframework.scheduling.annotation.Scheduled;  
  7. import org.springframework.stereotype.Component;  
  8.   
  9. /** 
  10.  * Spring靜態週期定時任務 
  11.  * @Author 許亮 
  12.  * @Create 2016-11-10 16:31:29 
  13.  */  
  14. @Lazy(false)  
  15. @Component  
  16. public class SpringStaticCronTask {  
  17.     private static final Logger logger = LoggerFactory.getLogger(SpringStaticCronTask.class);  
  18.       
  19.     @Scheduled(cron="0/5 * * * * ?")  
  20.     public void staticCronTask() {  
  21.         logger.debug("staticCronTask is running...");  
  22.     }  
  23.       
  24. }  

  上述任務適用於具有固定任務週期的任務,若要修改任務執行週期,只能走“停服務→修改任務執行週期→重啓服務”這條路。

  下面來看看可以在不停服務的情況下動態修改任務週期的實現,步驟如下:

  1. 在定時任務類上增加@EnableScheduling註解,並實現SchedulingConfigurer接口。(值得注意的是:@EnableScheduling對Spring的版本要求比較高,一開始使用的3.2.6版本時一直未成功,後來改成4.2.5版本就可以了)
  2. 設置一個靜態變量cron,用於存放任務執行週期參數。
  3. 另闢一線程,用於模擬實際業務中外部原因修改了任務執行週期。
  4. 設置任務觸發器,觸發任務執行,其中就可以修改任務的執行週期。

  完整的SpringDynamicCronTask.java代碼如下:

[java] view plain copy
  1. package com.pes_soft.task.demo;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import org.slf4j.Logger;  
  6. import org.slf4j.LoggerFactory;  
  7. import org.springframework.context.annotation.Lazy;  
  8. import org.springframework.scheduling.Trigger;  
  9. import org.springframework.scheduling.TriggerContext;  
  10. import org.springframework.scheduling.annotation.EnableScheduling;  
  11. import org.springframework.scheduling.annotation.SchedulingConfigurer;  
  12. import org.springframework.scheduling.config.ScheduledTaskRegistrar;  
  13. import org.springframework.scheduling.support.CronTrigger;  
  14. import org.springframework.stereotype.Component;  
  15.   
  16. /** 
  17.  * Spring動態週期定時任務<br> 
  18.  * 在不停應用的情況下更改任務執行週期 
  19.  * @Author 許亮 
  20.  * @Create 2016-11-10 16:31:29 
  21.  */  
  22. @Lazy(false)  
  23. @Component  
  24. @EnableScheduling  
  25. public class SpringDynamicCronTask implements SchedulingConfigurer {  
  26.     private static final Logger logger = LoggerFactory.getLogger(SpringDynamicCronTask.class);  
  27.       
  28.     private static String cron;  
  29.       
  30.     public SpringDynamicCronTask() {  
  31.         cron = "0/5 * * * * ?";  
  32.           
  33.         // 開啓新線程模擬外部更改了任務執行週期  
  34.         new Thread(new Runnable() {  
  35.             @Override  
  36.             public void run() {  
  37.                 try {  
  38.                     Thread.sleep(15 * 1000);  
  39.                 } catch (InterruptedException e) {  
  40.                     e.printStackTrace();  
  41.                 }  
  42.                   
  43.                 cron = "0/10 * * * * ?";  
  44.                 System.err.println("cron change to: " + cron);  
  45.             }  
  46.         }).start();  
  47.     }  
  48.   
  49.     @Override  
  50.     public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {  
  51.         taskRegistrar.addTriggerTask(new Runnable() {  
  52.             @Override  
  53.             public void run() {  
  54.                 // 任務邏輯  
  55.                 logger.debug("dynamicCronTask is running...");  
  56.             }  
  57.         }, new Trigger() {  
  58.             @Override  
  59.             public Date nextExecutionTime(TriggerContext triggerContext) {  
  60.                 // 任務觸發,可修改任務的執行週期  
  61.                 CronTrigger trigger = new CronTrigger(cron);  
  62.                 Date nextExec = trigger.nextExecutionTime(triggerContext);  
  63.                 return nextExec;  
  64.             }  
  65.         });  
  66.     }  
  67. }  

  將demo運行起來,查看任務執行情況,可以觀察到任務的執行週期由5秒變成了10秒,期間服務並未停止。

  

  源碼下載:mvc-task-dynamic-cron.rar

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章