google Analytics

Saturday, August 21, 2010

Job Scheduling with Spring

Job Scheduling with Spring
Scheduling support in Spring comes in two distinct forms: JDK Timer-based and Quartz-based.
The JDK Timer-based approach provides scheduling capabilities on any version 1.3 or later JVM,
and it does not need external dependencies beyond Spring. Timer-based scheduling is quite primitive
and provides limited flexibility when defining job schedules. However, Timer support is included
with Java and requires no external libraries, which might be beneficial if you are restricted by application
size or corporate policy. Quartz-based scheduling is much more flexible and allows triggers
to be defined in a much more real-world way, such as the earlier example of 3:00 p.m. every Monday,
Wednesday, and Friday

Scheduling Jobs Using JDK Timer
Creating a Simple Job
To create a job to use with the Timer class, you simply extend the TimerTask class and implement the
run() method to execute your job’s logic

public class HelloWorldTask extends TimerTask {
public void run() {
System.out.println("Hello World!");

import java.util.Timer;
public class OneOffScheduling {
public static void main(String[] args) {
Timer t = new Timer();
t.schedule(new HelloWorldTask(), 1000);

Scheduling a Repeating Task
public class FixedDelayScheduling {
public static void main(String[] args) throws Exception{
Timer t = new Timer();
t.schedule(new HelloWorldTask(), 1000, 3000);

import java.util.Timer;
public class FixedRateScheduling {
public static void main(String[] args) throws Exception {
Timer t = new Timer();
t.scheduleAtFixedRate(new HelloWorldTask(), 1000, 1000);
Spring Support for JDK Timer Scheduling
The core of Spring’s Timer support comes in the form of the ScheduledTimerTask and
TimerFactoryBean classes. The ScheduledTimerTask class acts as a wrapper around your TimerTask
implementations and allows you to define trigger information for the job. Using the TimerFactoryBean,
you can have Spring automatically create Timer instances for a given list of ScheduledTimerTask beans
using the trigger configuration data when creating the trigger

Configuring Job Scheduling Using TimerFactoryBean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=
<bean id="job" class="com.apress.prospring2.ch12.timer.HelloWorldTask"/>
<bean id="timerTask"
<property name="delay" value="1000" />
<property name="period" value="3000" />
<property name="timerTask" ref="job" />
<bean id="timerFactory"
<property name="scheduledTimerTasks">
<ref local="timerTask"/>

Scheduling Jobs Using OpenSymphony Quartz
Quartz provides a huge range of features such as persistent jobs, clustering,
and distributed transaction,The core of Quartz is made up of two interfaces, Job and Scheduler, and two classes, JobDetail
and Trigger

Scheduling jobs using Quartz or Timer
Dynamic Job Scheduling using Spring
Scheduling Jobs Using OpenSymphony Quartz

No comments:

Post a Comment