Scheduling tasks using Quartz

We had the need on a Spring-enabled project to schedule some tasks to run once in a while. BC pointed me towards Quartz, an open source Java scheduling service that plays well with Spring.

Here’s what I did to make it work.

Get the relevant jars

You can download the jars from the project website. Since we’re using Maven on this project, I just added this to the POM.xml:


Note that the standard Spring dependency includes some but not all of the Quartz classes. I need the full package to get the scheduling flexibility I needed, you may not need it.

Create a task

I created a task that I wanted to run periodically.

package ca.intelliware.sample.task;

public class SampleTask {

    private Log log = LogFactory.getLog(getClass());

    public void execute() {
        System.put.println("Starting sample task");

The method name is not important. It’s referenced in the Spring wiring below.

Tell Spring about the task

In the Spring configuration file:

<bean id="sampleTask" class="ca.intelliware.sample.task.SampleTask"/>

<bean id="sampleScheduledJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
  <property name="targetObject" ref="sampleTask" />
  <property name="targetMethod" value="execute"
  <property name="concurrent" value="false" />

<bean id="sampleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
  <property name="jobDetail" ref="sampleScheduledJob" />
  <property name="startDelay" value="10000" />              <!-- initiate 10 seconds after server starts -->
  <property name="repeatInterval" value="3600000" />        <!-- repeat every hour -->

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

When my application server starts up, the sample task runs after 10 seconds and then will run every hour after that. There are plenty of different timer configuration options, and the job definition and scheduling can just as easily be handled in Java code.

It's only fair to share...
Share on Facebook
Tweet about this on Twitter
Share on LinkedIn

Leave a Reply