Based on Quartz in Webapps, this shows how to use Spring to integrate Quartz:

  1. Add the JobDetails to the Spring context
  2. Add the Trigger to the Spring context
  3. Add the Scheduler to the Spring context
  4. Improve the Job implementation
  1. 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>
  2. 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>
  3. 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>
  4. 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");
        }
     
    }