配置有两种bean
- MethodInvokingJobDetailFactoryBean
- JobDetailFactoryBean
一.MethodInvokingJobDetailFactoryBean
在dispatcher-servlet.xml中配置
<!--quartz的bean之MethodInvokeJobDetailFactoryBean-->
<bean id="simpleJobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="myBean" />
<property name="targetMethod" value="printMessage" />
</bean>
MyBean这个类的编写
@Component("myBean")
public class MyBean {
public void printMessage() {
System.out.println("MyBean Executes");
}
}
二.JobDetailFactoryBean
需要给作业传递数据,想更加灵活的话就使用这种方式
在dispatcher-servlet.xml中的配置
<bean name="firstComplexJobDetail"
class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<!--jobClass关联到一个继承自QuartzJobBean接口的类-->
<property name="jobClass"
value="cn.springquartz.FirstScheduledJob"></property>
<!--jobDataMap是可选的,可以传入自己的一些参数-->
<property name="jobDataMap">
<map>
<entry key="anotherBean" value-ref="anotherBean"></entry>
</map>
</property>
<property name="durability" value="true" />
</bean>
FirstScheduledJob类
public class FirstScheduledJob extends QuartzJobBean {
private AnotherBean anotherBean;
public void setAnotherBean(AnotherBean anotherBean) {
this.anotherBean = anotherBean;
}
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//todo 实现业务逻辑
}
}
AnotherBean
@Component
public class AnotherBean {
public void hahah(){
//普通的类
}
}
三.Trigger的配置
<!--这下再来指定Trigger,simpleTrigger-->
<bean id="simpleTrigger"
class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<!--绑定simpleJobDetail-->
<property name="jobDetail" ref="simpleJobDetail" />
<!--距离当前时间1s后执行-->
<property name="startDelay" value="1000" />
<!--之后每隔2s执行一次-->
<property name="repeatInterval" value="2000" />
</bean>
<!--cronTrigger-->
<bean id="cronTrigger"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<!--绑定firstComplexJobDetail-->
<property name="jobDetail" ref="firstComplexJobDetail" />
<!--绑定Cron表达式-->
<property name="cronExpression" value="0/5 * * ? * *" />
</bean>
四.scheduler的配置
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<!--指定job-->
<property name="jobDetails">
<list>
<ref bean="simpleJobDetail"/>
<ref bean="firstComplexJobDetail" />
</list>
</property>
<!--指定trigger-->
<property name="triggers">
<list>
<ref bean="simpleTrigger"/>
<ref bean="cronTrigger" />
</list>
</property>
</bean>