Spring中使用quartz执行定时任务的两种方式
一, 继承spring封装Quartz类(org.springframework.scheduling.quartz.QuartzJobBean)方式
spring-mvc-quartz2.xml:
<bean id="job2Trigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail"> <bean class="org.springframework.scheduling.quartz.JobDetailBean"> <property name="jobClass" value="com.yueguang.schedule.Job2"/> <property name="jobDataAsMap"> <!-- 只能这么注入属性,不能在任务类里注入 --> <map><entry key="job2Service" value-ref="job2Service"/></map> </property> </bean> </property> <!-- 指定Cron表达式 --> <property name="cronExpression" value="0/1 * * * * ?"/> </bean> <bean id="schedulerFactory" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="job1Trigger" /> <!-- <ref bean="job2Trigger" /> --> </list> </property> </bean>
二,利用spring MethodInvokingJobDetailFactoryBean类,不需要继承.
spring-mvc-quartz1.xml
<!-- job bean 配置 --> <bean id="job1" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="job1bean" /> <property name="targetMethod" value="justDoIt" /> <property name="concurrent" value="true" /> <!-- 设置为true则多个job并发执行 --> </bean> <!-- trigger --> <bean id="job1Trigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="job1" /> <property name="cronExpression" value="0/1 * * * * ?" /> </bean> <!-- 定时任务调度器 --> <bean id="schedulerFactory" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="job1Trigger" /> <!-- <ref bean="job2Trigger" /> --> </list> </property> </bean>
注:
1,在第一种方式中,不能在jobbean中直接以注解的方式注入spring bean组件,必须在jobDetail的属性jobDataAsMap中配置要注入的bean组件,同时需要在该jobbean中写好对应的setter.
2,下面的项目是maven项目.