Job Scheduling Example using Simple Trigger in Spring

The Spring Framework features integration classes for scheduling support. Currently, Spring supports the Quartz Scheduler ( Schedulers are set up using a FactoryBean with optional references to Trigger instances.

Defining Job

<bean name="exampleJob" class="org.springframework.scheduling.quartz.JobDetailBean">
  <property name="jobClass" value="example.ExampleJob" />
  <property name="jobDataAsMap">
      <entry key="timeout" value="5" />

JobDetail objects contain all information needed to run a job. The Spring Framework provides a JobDetailBean that makes the JobDetail more of an actual JavaBean with sensible defaults. The job detail bean has all information it needs to run the job (ExampleJob). The timeout is specified in the job data map. The job data map is available through the JobExecutionContext (passed to you at execution time), but the JobDetailBean also maps the properties from the job data map to properties of the actual job. So in this case, if the ExampleJob contains a property named timeout, the JobDetailBean will automatically apply it:

package example;

public class ExampleJob extends QuartzJobBean {
  private int timeout;

   * Setter called after the ExampleJob is instantiated with the value from the JobDetailBean (5)
  public void setTimeout(int timeout) {
    this.timeout = timeout;

  protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
    // do the actual work

Wiring up Job

We've created job details and jobs. Of course, we still need to schedule the jobs themselves. This is done using Scheduling triggers and a SchedulerFactoryBean.Triggers need to be scheduled. Spring offers a SchedulerFactoryBean that exposes triggers to be set as properties. SchedulerFactoryBean schedules the actual jobs with those triggers.

Find below an example:

<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
  <!-- see the example of method invoking job above -->
  <property name="jobDetail" ref="jobDetail" />
  <!-- 10 seconds -->
  <property name="startDelay" value="10000" />
  <!-- repeat every 50 seconds -->
  <property name="repeatInterval" value="50000" />
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
  <property name="jobDetail" ref="exampleJob" />
  <!-- run every morning at 6 AM -->
  <property name="cronExpression" value="0 0 6 * * ?" />

Now we've set up a trigger, running every 50 seconds with a starting delay of 10 seconds. To finalize everything, we need to set up the SchedulerFactoryBean:

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  <property name="triggers">
      <ref bean="cronTrigger" />
      <ref bean="simpleTrigger" />

No comments:

Post a Comment