不繼承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