1. 程式人生 > >spring3使用task註記及task:annotation-driven解決定時問題

spring3使用task註記及task:annotation-driven解決定時問題

轉載自:http://kennylee26.iteye.com/blog/1965291

最近發現真的凹凸了,Spring升級到3後原來已經自帶任務排程器了,之前還一直使用著Quartz。其實也不是Quartz不好,只是相比之下,使用Spring task真的簡單很多,無論是理解還是使用。

Spring Task提供兩種方式進行配置,正如大家所想吧,還是一種是annotation(標註),而另外一種就是XML配置了。但其實這裡我覺得比較尷尬,因為任務排程這樣的需求,通常改動都是比較多的,如果用annotation的方式的話,改動就變得麻煩了,必須去重新編譯。所以,我只是選擇用XML配置的方式,不過我還是習慣性地啟用著標註方式,就如AOP配置那樣。annotation方式請自行查詢@Scheduled

具體配置參考如下即可

Xml程式碼  收藏程式碼
  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" xmlns:task="http://www.springframework.org/schema/task"  
  4.     xsi:schemaLocation="  
  5.           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  6.           http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">  
  7.     <bean id="reminderProcessor" class="com.foo.task.ReminderProcessor">  
  8.         <property name="workers">  
  9.             <array value-type="com.foo.task.Worker">  
  10.                 <
    ref bean="projectScheduleRemindWorker" />  
  11.             </array>  
  12.         </property>  
  13.     </bean>  
  14.     <!-- 配置任務線性池 -->  
  15.     <task:executor id="executor" pool-size="3" />  
  16.     <task:scheduler id="scheduler" pool-size="3" />  
  17.     <!-- 啟用annotation方式 -->  
  18.     <task:annotation-driven scheduler="scheduler"  
  19.         executor="executor" proxy-target-class="true" />  
  20.     <task:scheduled-tasks scheduler="scheduler">  
  21.         <task:scheduled ref="reminderProcessor" method="process"  
  22.             cron="0 0 12 * * ?" />  
  23.     </task:scheduled-tasks>  
  24. </beans>  

核心部分見

Xml程式碼  收藏程式碼
  1. <task:scheduled-tasks scheduler="scheduler">  
  2. <task:scheduled ref="reminderProcessor" method="process"  
  3. cron="0 0 12 * * ?" />  
  4. </task:scheduled-tasks>  

意思就是每天的12點執行reminderProcessor這個Bean中的process方法。cron的配置表示式跟Quartz基本一致,但實測不支援一些特殊字元,如配置天的時候的L,W和Z,因為遇到要每個月倒數第三天執行任務排程的需求,但我一配置SpringTask報非法字元。

所以,Quartz和SpringTask間的差距也顯而易見的。SpringTask用起來十分簡單,畢竟是Spring自家的,雖然跟Quartz也可以實現結合,但沒那麼簡單。而SpringTask功能也沒Quartz強大,Quartz的叢集和高階特性多的去了。所以大家可以自行選擇了。不過一般情況下,覺得SpringTask足夠了。

附上我這個例子的詳細UML說明