Spring-task 定時任務
版本
spring-instrument是從spring3.0以後加入的,注意版本問題。
使用方式
1.增加標籤庫
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd ">
2.開啓註解
<!-- 執行線程池 -->
<task:executor id="executor" pool-size="5" />
<!-- 調度線程池 -->
<task:scheduler id="scheduler" pool-size="5" />
<!-- task掃描 -->
<task:annotation-driven executor="executor" scheduler="scheduler" />
3.@Scheduled註解使用方式
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class SpringTaskAnnotation {
@Scheduled(cron = "0/5 * * * * ?")
public void run(){
System.out.println("=======================1");
}
@Scheduled(cron = "0/5 * * * * ?")
public void run2(){
System.out.println("=======================2");
}
}
4.配置使用方式
<!-- xml方式 -->
<task:scheduled-tasks scheduler="scheduler">
<task:scheduled ref="springTaskXml" method="run" cron="0/5 * * * * ?" />
<task:scheduled ref="springTaskXml" method="run2" cron="0/5 * * * * ?" />
</task:scheduled-tasks>
原理介紹
spring在初始化bean後,通過“ScheduledAnnotationBeanPostProcessor.postProcessAfterInitialization”攔截到所有的用到“@Scheduled”註解的方法,並解析相應的的註解參數,放入“定時任務列表”等待後續處理;之後再“定時任務列表”中統一執行相應的定時任務(任務爲順序執行,先執行cron,之後再執行fixedRate)。
initial-delay是任務第一次被調用前的延時,單位毫秒(方法第一次調用時延遲)
fixed-delay是上一個調用完成後再次調用的延時
fixed-rate是上一個調用開始後再次調用的延時(不用等待上一次調用完成)
cron是表達式,表示在什麼時候進行任務調度。
如果多個定時任務定義的是同一個時間,那麼也是順序執行的,會根據程序加載Scheduled方法的先後來執行。
但是如果某個定時任務執行未完成,此任務一直無法執行完成,無法設置下次任務執行時間,之後會導致此任務後面的所有定時任務無法繼續執行,也就會出現所有的定時任務“失效”現象。
可以儘量把定時任務“分散”下。
優點
使用非常簡單,配置好之後只需要在實現類上增加註解即可。避免複雜配置
spring自家產品,除spring相關的包外不需要額外引入額外jar包
支持註解和配置文件兩種形式
支持線程池調度
缺點
策略配置到類中,涉及修改策略會變的比較複雜
不易管理,定時器只需要增加註解,隨處可加
spring的定時任務默認是單線程,多個任務執行起來時間會有問題(B任務會因爲A任務執行起來需要20S而被延後20S執行)
官方文檔
http://docs.spring.io/spring/docs/3.2.9.RELEASE/javadoc-api/
使用場景
//待續
容災策略
//待續