spring3使用task註記及task:annotation-driven解決定時問題
阿新 • • 發佈:2019-02-10
轉載自:http://kennylee26.iteye.com/blog/1965291
最近發現真的凹凸了,Spring升級到3後原來已經自帶任務排程器了,之前還一直使用著Quartz。其實也不是Quartz不好,只是相比之下,使用Spring task真的簡單很多,無論是理解還是使用。
Spring Task提供兩種方式進行配置,正如大家所想吧,還是一種是annotation(標註),而另外一種就是XML配置了。但其實這裡我覺得比較尷尬,因為任務排程這樣的需求,通常改動都是比較多的,如果用annotation的方式的話,改動就變得麻煩了,必須去重新編譯。所以,我只是選擇用XML配置的方式,不過我還是習慣性地啟用著標註方式,就如AOP配置那樣。annotation方式請自行查詢@Scheduled
具體配置參考如下即可
Xml程式碼- <?xml version="1.0" encoding="UTF-8"?>
- <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"
- 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">
- <bean id="reminderProcessor" class="com.foo.task.ReminderProcessor">
- <property name="workers">
- <array value-type="com.foo.task.Worker">
-
<
- </array>
- </property>
- </bean>
- <!-- 配置任務線性池 -->
- <task:executor id="executor" pool-size="3" />
- <task:scheduler id="scheduler" pool-size="3" />
- <!-- 啟用annotation方式 -->
- <task:annotation-driven scheduler="scheduler"
- executor="executor" proxy-target-class="true" />
- <task:scheduled-tasks scheduler="scheduler">
- <task:scheduled ref="reminderProcessor" method="process"
- cron="0 0 12 * * ?" />
- </task:scheduled-tasks>
- </beans>
核心部分見
Xml程式碼- <task:scheduled-tasks scheduler="scheduler">
- <task:scheduled ref="reminderProcessor" method="process"
- cron="0 0 12 * * ?" />
- </task:scheduled-tasks>
意思就是每天的12點執行reminderProcessor這個Bean中的process方法。cron的配置表示式跟Quartz基本一致,但實測不支援一些特殊字元,如配置天的時候的L,W和Z,因為遇到要每個月倒數第三天執行任務排程的需求,但我一配置SpringTask報非法字元。
所以,Quartz和SpringTask間的差距也顯而易見的。SpringTask用起來十分簡單,畢竟是Spring自家的,雖然跟Quartz也可以實現結合,但沒那麼簡單。而SpringTask功能也沒Quartz強大,Quartz的叢集和高階特性多的去了。所以大家可以自行選擇了。不過一般情況下,覺得SpringTask足夠了。
附上我這個例子的詳細UML說明