Spring整合Quartz有两种方式:
一是通过Spring的JobDetailBean
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>
其中jobClass的Value值指向自己所写的job类,此类必须继承Spring的QuartzJobBean,并重写executeInternal方法,jobDataAsMap中注入的值,即为在executeInternal方法中通过context.getMergedJobDataMap().get方法获得的值。
example.ExampleJob的代码如下
package example; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.scheduling.quartz.QuartzJobBean; 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; // } @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { System.out.println(context.getMergedJobDataMap().get("out")); System.out.println("executeInternal ............"); } }
二是通过MethodInvokingJobDetailFactoryBean
MethodInvokingJobDetailFactoryBean的配置如下
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="exampleBusinessObject" /> <property name="targetMethod" value="doIt" /> </bean>
targetObject所注入的即为自己所写的job类,此类可以是普通的java类,不需继承或实现任何接口。targetMethod的值即为job类的内部方法
exampleBusinessObject的代码如下
package example; public class ExampleBusinessObject { // properties and collaborators public void doIt() { System.out.println("do it .............."); // do the actual work } }
无论是通过上面哪一种方法,都必须为他们建立自己的触发器Trigger,Spring中提供了两种触发器,CronTriggerBean,SimpleTriggerBean,具体可以自由选择用哪种。
两种方式的配置如下
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <!-- see the example of method invoking job above --> <property name="jobDetail" ref="jobDetail" /> <!-- 10 seconds --> <property name="startDelay" value="10000" /> <!-- repeat every 50 seconds --> <property name="repeatInterval" value="50000" /> </bean> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="exampleJob" /> <!-- run every morning at 6 AM --> <property name="cronExpression" value="0 0 6 * * ?" /> </bean>
最后,关键的一步,把上面配置好的触发器注入到SchedulerFactoryBean中去
配置文件如下
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="cronTrigger" /> <ref bean="simpleTrigger" /> </list> </property> </bean>
好了,Spring的中的定时任务已经配置好了,现在可以去你的job类里为所欲为了!
ps:Spring的版本的和Quartz的版本问题需要注意,spring 3.X的可以用Quartz2.x,spring2.x的就只能用Quartz1.x的了!切记。。。