動態改變spring定時任務執行頻率


 

http://blog.csdn.net/qq_27063119/article/details/54926406

**********************************************************************

一.引入

    由於公司門戶系統需要定時推送數據進國家平台,所以首先想到的是利用spring的定時任務進行定時推送,當然對於這種需求比較簡單,如下操作即可:

    1.打開任務調度使用,在applicationContext.xml中添加  <task:annotation-driven />,即配置打開了任務調度

當然注意了:頭文件上需要加上

 

<beans xmlns="http://www.springframework.org/schema/beans"    
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
    xmlns:task="http://www.springframework.org/schema/task"    
    xmlns:context="http://www.springframework.org/schema/context"    
    xsi:schemaLocation="    
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd    
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd     
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> 

 

    2.自定義一個 任務調度的類,這里我寫為了:MyScheduler.Java ,為了讓spring能夠管理到,加上了Component注解,然后方法上加上Scheduled注解,進行配置調度的頻率(1000*60)-代表1分鍾調用一次

 

      @Component("scheduledTaskManager")  
      public class MyScheduler {  
      
       @Scheduled(fixedRate = 1000*60)  
       public void heartbeat() {  
    //任務邏輯  
      
         }  
     }  

 

這樣配置就結束了,很簡單明了。


二.動態修改調度頻率

    通過上述的配置,已經實現了簡單的定時任務調度,但是這中寫法不適宜動態修改,至少我還沒有按照上述的寫法動態修改頻率成功過,於是,這里寫一下另外一種寫法:

    定義一個任務類:updateCronTask.java,這個類實現SchedulingConfigurer接口的configureTasks方法

 

        @Component  
        @EnableScheduling  
        public class updateCronTask implements SchedulingConfigurer {    
             
            public static String cron = "0/2 * * * * ?";    
            int i=0;  
          
            @Override    
            public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {  
                taskRegistrar.addTriggerTask(new Runnable() {    
                @Override    
                public void run(){  
                i++;  
                    // 任務邏輯    
                System.out.println("第"+(i)+"次開始執行操作... " +"時間:【" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS").format(new Date()) + "】");  
                      
                }  
            }, new Trigger(){  
                @Override  
                public Date nextExecutionTime(TriggerContext triggerContext) {  
                    //任務觸發,可修改任務的執行周期   
                    CronTrigger trigger = new CronTrigger(cron);  
                    Date nextExec = trigger.nextExecutionTime(triggerContext);  
                    return nextExec;    
                }  
            });  
        }  
    }  

 

項目啟動后,只要觸發改變cron的參數即可實現動態 修改任務調度頻率,如:測試在controller層中,當訪問了 某個url后,觸發改變了cron 的參數,達到了預期的效果。

開始默認的頻率是2s /次,后來通過controller層進行修改成了10s /次,

如果你有更好的方法,記得分享出來。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM