首页 / 操作系统 / Linux / Spring整合Quartz的方法
一、增加所依赖的JAR包 1、增加Spring的Maven依赖 Xml代码
<dependency> <groupId> org.springframework</groupId> <artifactId> spring-webmvc</artifactId> <version> 3.0.5.RELEASE</version> </dependency> 2、增加Quartz的Maven依赖 Xml代码
< dependency > < groupId > org.quartz-scheduler </ groupId > < artifactId > quartz </ artifactId > < version > 1.8.4 </ version > </ dependency > 二、Spring整合Quartz的两种方法 1、使用JobDetailBean 创建job,继承QuartzJobBean ,实现 executeInternal(JobExecutionContext jobexecutioncontext)方法。这种方法和在普通的Quartz编程中是一样的。 JobDetail对象包含运行一个job的所有信息。 Spring Framework提供了一个JobDetailBean,包含运行一个job的所有信息。 Xml代码
<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> job data map(jobDataAsMap)可通过JobExecutionContext (执行时传递)获取。JobDetailBean将 job data map的属性映射到job的属性。如例所示,如果job类中包含一个job data map中属性,JobDetailBean将自动应用,可用于传递参数: Java代码
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 } } 2、使用MethodInvokingJobDetailFactoryBean 通过MethodInvokingJobDetailFactoryBean在运行中动态生成,需要配置执行任务的目标类、目标方法。但是这种方法动态生成的JobBean不支持序列号,也就是说Job不能存到持久化。 通常用于调用特定对象的一个方法。不用创建单独的job对象,只需要建立正常的业务对象,用这样方式去调用其中的一个方法。 Xml代码
<bean id ="jobDetail" class ="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" > <property name ="targetObject" ref ="exampleBusinessObject" /> <property name ="targetMethod" value ="doIt" /> <property name ="arguments" > <list> <!-- a primitive type (a string) --> <value> 1st</value> <!-- an inner object definition is passed as the second argument --> <object type ="Whatever.SomeClass, MyAssembly" /> <!-- a reference to another objects is passed as the third argument --> <ref object ="someOtherObject" /> <!-- another list is passed as the fourth argument --> <list> <value> http://www.springframework.net/</value> </list> </list> </property> <property name ="concurrent" value ="false" /> </bean>
收藏该网址