Vineet Manohar is CTO / Co-Founder of online Car Search Engine, iSeeCars.com. Vineet is a DZone MVB and is not an employee of DZone and has posted 20 posts at DZone. You can read more from them at their website. View Full User Profile

Spring Quartz Code Snippets for Beginners

10.12.2010
| 11142 views |
  • submit to reddit

Some applications need to run periodic jobs in the background. On Linux/Unix systems, background processes can be run using the “cronjob” scheduling service. In Java web applications, you can add scheduling to any app in 4 simple steps using Spring and Quartz. This article outlines the steps needed for scheduling, with code snippets required for each step.

Step 1: web.xml

To initialize Spring in your webapp, add this snippet to your web.xml file. If you are already using Spring, you probably already have this in your web.xml.

<!-- Initialize Spring -->
<listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Step 2: applicationContext.xml snippet

There are 3 concepts when configuring your scheduled jobs:

1) The Job: the java code that you want to run in the background periodically

2) A Trigger: a trigger adds scheduling information to your job. There are different types of triggers (e.g. SimpleTrigger, CronTrigger). They differ in the way you specify scheduling information. For example, CronTrigger takes a cronexpression, whereas SimpleTrigger takes a repeatInterval.

3) The Scheduler: this is the actual service which runs in the background and invokes ‘triggers’. You can register multiple triggers with this service.

Add this snippet to your Spring xml file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
 "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

 <!-- The 'Scheduler': quartz scheduler -->
 <bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  <!-- list of triggers registered with the scheduler -->
  <property name="triggers">
   <list>
    <!-- Trigger1: JobExample using CronTrigger -->
    <bean id="jobDetailTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
     <!-- job class -->
     <property name="jobDetail">
      <bean class="org.springframework.scheduling.quartz.JobDetailBean">
       <!-- CHANGE THIS to the actual implementation class (see step 4)  -->
       <property name="jobClass" value="com.vineetmanohar.example.quartz.JobExample" />
      </bean>
     </property>

     <!-- job schedule: every 5 minutes: CHANGE THIS -->
     <property name="cronExpression" value="0 0/30 * * * ?" />
    </bean>

    <!-- Trigger2: JobExample2 using SimpleTrigger -->
    <bean class="org.springframework.scheduling.quartz.SimpleTriggerBean">
     <property name="jobDetail">
      <bean>
       <!-- CHANGE THIS to the actual implementation class (see step 4)  -->
       <property name="jobClass" value="com.vineetmanohar.example.quartz.JobExample2" />
      </bean>
     </property>

     <!-- wait 4 minutes after startup -->
     <property name="startDelay" value="240000" />

     <!-- every 1 min (60 sec) -->
     <property name="repeatInterval" value="60000" />
    </bean>
   </list>
  </property>
 </bean>

</beans>

Step 3: pom.xml snippet

If you are using Maven, add this to your pom.xml to add Spring and Quartz dependency to your project.

<project>
 <dependencies>
  <dependency>
   <groupId>org.opensymphony.quartz</groupId>
   <artifactId>quartz</artifactId>
   <version>1.6.1</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>2.5</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context-support</artifactId>
   <version>2.5</version>
  </dependency>
 </dependencies>
</project>

Step 4: Java code snippet

Finally, write the actual implementation. Make sure that job class you specified in step 2 points to this file.

package com.vineetmanohar.example.quartz.JobExample;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class JobExample extends QuartzJobBean {
  protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
   System.out.println("Job invoked at : " + new java.util.Date());

   // TODO: implement the job here
 }
}

Cron expression

The format of cron expression is <Seconds> <Minutes> <Hours> <Day-of-Month> <Month> <Day-of-Week> <Year (optional field)>. For example:

Every 30 minutes

0 0/30 * * * ? 

See full reference documentation here.

From http://www.vineetmanohar.com/2010/10/spring-quartz-code-snippets-for-beginners

Published at DZone with permission of Vineet Manohar, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Martijn Verburg replied on Tue, 2010/10/12 - 8:13am

Would be interesting to see a re-work of the the examples with the latest version of quartz, it's moved to http://www.quartz-scheduler.org/ and sits at version 1.8.3.  1.6.1 and pals weren't always the most bug free of versions :)

Cheers,

Martijn (@java7developer - twitter)

Lajos Papp replied on Wed, 2010/10/13 - 5:57am

Or how about using the new task namspace from spring 3.0:
<task:scheduled-tasks>
   <task:scheduled ref="simpleProcessor" method="process" cron="3/10 * * * * ?"/>
</task:scheduled-tasks>

michael cheung replied on Mon, 2010/10/18 - 1:12am

We have 20 jobs in quartz. the spring file become unmanagable. It will be nice if the jobDetail and CronTrigger can be wired using using @Component. There isn't any UI for quartz. I want to change the datasource to be backed by a database so I have a cluster of quart servers running. If you are thinking rewriting your batch job or scheduler, I suggest you check out spring batch.

Steven Harris replied on Fri, 2010/10/22 - 6:40pm

If your really elite you'll check out the new quartz 2.0 API's (still under dev but going beta soon). James is making things much simpler cleaner and easier to code. It's really quite elegant.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.