Spring 端:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
Quartz 端:
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>1.8.4</version>
</dependency>
建立 job 時繼承 QuartzJobBean,實作 executeInternal(JobExecutionContext) 方法,這部分與原生 Quartz 編程完全相同。差別在於 JobDetail 的宣告交給 Spring 的 JobDetailBean 來描述:
<bean name="exampleJob" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="example.ExampleJob" />
<property name="jobDataAsMap">
<map>
<entry key="timeout" value="5" />
</map>
</property>
</bean>
jobDataAsMap 平時可透過 JobExecutionContext 取得,而 JobDetailBean 會把 map 裡的屬性自動對應到 job 的同名屬性上,等於多了一條傳參數的通道:
public class ExampleJob extends QuartzJobBean{
private int timeout;
/**
* Setter called after the ExampleJob is instantiated
* with the value from the JobDetailBean (5)
*/
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* 業務邏輯處理
*/
protected void executeInternal(JobExecutionContext ctx)
throws JobExecutionException {
// do the actual work
}
}
這種方式的優點是 job 由 Spring 管理,因此可以直接注入 Service、DAO 等 bean,也支援序列化與持久化。
這種做法在執行期動態產生 Job,只需指定目標物件與目標方法,不必另外寫一個 job 類別:
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="exampleBusinessObject" />
<property name="targetMethod" value="doIt" />
<property name="arguments">
<list>
<value>1st</value>
<object type="Whatever.SomeClass, MyAssembly" />
<ref object="someOtherObject" />
<list>
<value>https://www.springframework.net/</value>
</list>
</list>
</property>
<property name="concurrent" value="false" />
</bean>
它最適合「觸發既有業務物件上的某個方法」這類場景,不必為此額外建 job。但有一個重要限制:動態產生的 JobBean 不支援序列化,也就是說這個 Job 無法被持久化到資料庫,叢集與重啟後的恢復能力隨之喪失。
選擇建議很明確:需要持久化、需要叢集、需要注入依賴,就用 JobDetailBean;只是想定時呼叫一個方法,MethodInvokingJobDetailFactoryBean 更省事。另外別忘了 concurrent 設為 false,避免同一個 Job 疊在一起執行。