August 25, 2009

Spring Quartz Example

« Spring Scheduler - ScheduledTimerTask | Main | Create new Maven Plugin »

Quartz represents an enterprise job scheduler. The mechanism of Quartz can be compared to Linux Cron jobs or JDK Timers. Spring integrates Quartz to offer scheduling and thread pooling features.

The following example describes two scheduling triggers/jobs. Triggers define the scheduling interval or the exact time of job execution. The SchedulerFactory references the triggers and initiates the scheduling.

<bean name="checkFTPForUpdates" class="org.springframework.scheduling.quartz.JobDetailBean">
  <property name="jobClass" value="org.developers.blog.example.spring.CheckFTPJob" />
</bean>

<bean name="checkDBForNewOrders" class="org.springframework.scheduling.quartz.JobDetailBean">
  <property name="jobClass" value="org.developers.blog.example.spring.CheckOrderDBJob" />
</bean>

<bean id="cronFTPCheckTriggerBean" class="org.springframework.scheduling.quartz.CronTriggerBean">
    <property name="jobDetail" ref="checkFTPForUpdates" />
    <!-- run at 14 PM every day -->
    <property name="cronExpression" value="0 0 14 * * ?" />
</bean>

<bean id="cronOrdersCheckTriggerBean" class="org.springframework.scheduling.quartz.CronTriggerBean">
    <property name="jobDetail" ref="checkDBForNewOrders" />
    <!-- run at 17 PM every day -->
    <property name="cronExpression" value="0 0 17 * * ?" />
</bean>

<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="triggers">
        <list>
            <ref bean="cronFTPCheckTriggerBean" />
            <ref bean="cronOrdersCheckTriggerBean" />
        </list>
    </property>
</bean>
The Job classes have the following structure.
public class CheckFTPJob extends QuartzJobBean {
  protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
      // check FTP
  }
}
public class CheckOrderDBJob extends QuartzJobBean {
  protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
      // check DB
  }
}
Regards
Rafael Sobek

Technorati Tags:

Posted by rafael.sobek at 8:36 PM in Spring

 

[Trackback URL for this entry]

Comment: Himanshu at Mo, 11 Jan 10:30 AM

Nice article but I have a query. How the method in Job classes would be invoked? I mean how the JobExecutionContext ref would be obtained by calling class? I tried your example but now I'm stuck. Please do reply

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
« August »
SunMonTueWedThuFriSat
      1
2345678
9101112131415
16171819202122
23242526272829
3031