歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Spring整合Quartz的方法

Spring整合Quartz的方法

日期:2017/3/1 10:35:30   编辑:Linux編程
一、增加所依賴的JAR包

1、增加Spring的Maven依賴

Xml代碼
  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-webmvc</artifactId>
  4. <version>3.0.5.RELEASE</version>
  5. </dependency>

2、增加Quartz的Maven依賴

Xml代碼
  1. < dependency >
  2. < groupId > org.quartz-scheduler </ groupId >
  3. < artifactId > quartz </ artifactId >
  4. < version > 1.8.4 </ version >
  5. </ dependency >

二、Spring整合Quartz的兩種方法

1、使用JobDetailBean

創建job,繼承QuartzJobBean ,實現 executeInternal(JobExecutionContext jobexecutioncontext)方法。這種方法和在普通的Quartz編程中是一樣的。

JobDetail對象包含運行一個job的所有信息。 Spring Framework提供了一個JobDetailBean,包含運行一個job的所有信息。

Xml代碼
  1. <bean name="exampleJob" class="org.springframework.scheduling.quartz.JobDetailBean">
  2. <property name="jobClass" value="example.ExampleJob" />
  3. <property name="jobDataAsMap">
  4. <map>
  5. <entry key="timeout" value="5" />
  6. </map>
  7. </property>
  8. </bean>

job data map(jobDataAsMap)可通過JobExecutionContext (執行時傳遞)獲取。JobDetailBean將 job data map的屬性映射到job的屬性。如例所示,如果job類中包含一個job data map中屬性,JobDetailBean將自動應用,可用於傳遞參數:

Java代碼
  1. public class ExampleJob extends QuartzJobBean{
  2. private int timeout;
  3. /**
  4. * Setter called after the ExampleJob is instantiated with the value from
  5. * the JobDetailBean (5)
  6. */
  7. public void setTimeout(int timeout) {
  8. this.timeout = timeout;
  9. }
  10. /**
  11. *
  12. * 業務邏輯處理
  13. *
  14. */
  15. protected void executeInternal(JobExecutionContext ctx)
  16. throws JobExecutionException {
  17. // do the actual work
  18. }
  19. }

2、使用MethodInvokingJobDetailFactoryBean

通過MethodInvokingJobDetailFactoryBean在運行中動態生成,需要配置執行任務的目標類、目標方法。但是這種方法動態生成的JobBean不支持序列號,也就是說Job不能存到持久化。

通常用於調用特定對象的一個方法。不用創建單獨的job對象,只需要建立正常的業務對象,用這樣方式去調用其中的一個方法。

Xml代碼

  1. <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
  2. <property name="targetObject" ref="exampleBusinessObject" />
  3. <property name="targetMethod" value="doIt" />
  4. <property name="arguments">
  5. <list>
  6. <!-- a primitive type (a string) -->
  7. <value>1st</value>
  8. <!-- an inner object definition is passed as the second argument -->
  9. <object type="Whatever.SomeClass, MyAssembly" />
  10. <!-- a reference to another objects is passed as the third argument -->
  11. <ref object="someOtherObject" />
  12. <!-- another list is passed as the fourth argument -->
  13. <list>
  14. <value>http://www.springframework.net/</value>
  15. </list>
  16. </list>
  17. </property>
  18. <property name="concurrent" value="false" />
  19. </bean>
Copyright © Linux教程網 All Rights Reserved