作业类是否继承QuartzJobBean
- 继承
- 不继承
不继承QuartzJobBean,声明JobDetail时,使用MethodInvokingJobDetailFactoryBean
继承QuartzJobBean,声明JobDetail时,使用JobDetailFactoryBean
任务调度的触发时机
- 每隔指定时间触发一次:触发器使用SimpleTriggerBean
- 每到指定时间触发一次:触发器使用CronTriggerBean
这两种触发方式都可以和两种作业继承方式相互组合来使用。
也就是有四种写法。
举个例子:
不继承QuartzJobBean,由SimpleTriggerBean触发
<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");
}
}
不继承QuartzJobBean,由CronTriggerBean触发
继承QuartzJobBean,由SimpleTirggerBean触发
继承QuartzJobBean,由CronTriggerBean触发
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中声明。
小菜虫使用jobDataMap
属性传递AnotherBean失败,原因不明。。。日后填坑。