不继承QuartzJobBean,声明JobDetail时,使用MethodInvokingJobDetailFactoryBean
spring
继承QuartzJobBean,声明JobDetail时,使用JobDetailFactoryBean
ui
<bean id="simpleJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="myBean"/> <property name="targetMethod" value="printMessage"/> </bean> <!-- Run the job every 2 seconds with initial delay of 1 second --> <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"> <property name="jobDetail" ref="simpleJobDetail"/> <property name="startDelay" value="1000"/> <property name="repeatInterval" value="2000"/> </bean>
public class MyBean { public void printMessage(){ System.out.println("不继承QuartzJobBean的做业类。called by MethodInvokingJobDetailFactoryBean using SimpleTriggerFactoryBean"); } }
public class ScheduledJob extends QuartzJobBean { private AnotherBean anotherBean; protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { anotherBean.printMessage(); } public void setAnotherBean(AnotherBean anotherBean) { this.anotherBean = anotherBean; } }
public class AnotherBean { public void printMessage(){ System.out.println("继承QuartzJobBean的做业类,经过AnotherBean传递数据。called by JobDetailFactoryBean using CronTriggerFactoryBean"); } }
<!-- For times when you need more complex processing, passing data to the scheduled job --> <bean name="complexJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean"> <property name="jobClass" value="com.penelope.quickstart.jobs.ScheduledJob"/> <property name="jobDataAsMap"> <map> <entry key="anotherBean" value-ref="anotherBean"/> </map> </property> <property name="durability" value="true"/> </bean> <!-- Run the job every 5 seconds only on Weekends --> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail" ref="complexJobDetail"/> <property name="cronExpression" value="0/5 * * ? * SAT-SUN"/> </bean>
第二个例子是复杂的,在任务类中调用另外一个Bean的方法。另外一个Bean就是该做业类的JobData。使用jobDataAsMap
属性,在JobDetail中声明。this
小菜虫使用jobDataMap
属性传递AnotherBean失败,缘由不明。。。往后填坑。code