Based on Quartz in Webapps, this shows how to use Spring to integrate Quartz:
- Add the JobDetails to the Spring context
- Add the Trigger to the Spring context
- Add the Scheduler to the Spring context
- Improve the Job implementation
Add the JobDetails to the Spring context:
There goes the “message” parameter again. The “applicationContextJobDataKey” is needed to access the Spring context from within the Job.<bean id="exampleJob" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="example.ExampleJob"/>
<property name="applicationContextJobDataKey" value="springContext"/>
<property name="jobDataAsMap">
<map><entry key="message" value="Hello Spring"/></map>
</property>
</bean>Add the Trigger to the Spring context:
Again, 4 executions with 10 seconds intervalls. This time, we delay the startup by 5 seconds.<bean id="exampleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="exampleJob"/>
<property name="startDelay" value="5000"/>
<property name="repeatCount" value="3"/>
<property name="repeatInterval" value="10000"/>
</bean>Add the Scheduler to the Spring context:
This factory bean adds the tigger to the scheduler and launches the scheduler.<bean name="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list><ref bean="exampleTrigger"/></list>
</property>
</bean>Improve the Job implementation:
Now, we may access our “message” using a local field! Furthermore, we have access to the Spring context.package example;
import org.quartz.JobExecutionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class ExampleJob extends QuartzJobBean {
private String message;
public void setMessage(String value) {
message = value;
}
protected void executeInternal(JobExecutionContext context) {
System.err.println(message);
ApplicationContext ctx = (ApplicationContext)
context.getJobDetail().getJobDataMap().get("springContext");
}
}