Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

Scheduling Recurring Tasks In Java Applications

By Tom White
2004-01-23


Scheduling a one-shot task

The scheduling framework is built on top of the Java timer framework classes. Therefore, we'll first look at scheduling using these classes before I explain how the scheduling framework is used and how it is implemented.

Imagine an egg timer that tells you when a number of minutes have elapsed (and therefore that your egg is cooked) by playing a sound. The code in Listing 1 forms the basis for a simple egg timer written in the Java language:

Listing 1. EggTimer class


package org.tiling.scheduling.examples;

import java.util.Timer;
import java.util.TimerTask;

public class EggTimer {
private final Timer timer = new Timer();
private final int minutes;

public EggTimer(int minutes) {
this.minutes = minutes;
}

public void start() {
timer.schedule(new TimerTask() {
public void run() {
playSound();
timer.cancel();
}
private void playSound() {
System.out.println("Your egg is ready!");
// Start a new thread to play a sound...
}
}, minutes * 60 * 1000);
}

public static void main(String[] args) {
EggTimer eggTimer = new EggTimer(2);
eggTimer.start();
}

}


An EggTimer instance owns a Timer instance to provide the necessary scheduling. When the egg timer is started using the start() method, it schedules a TimerTask to execute after the specified number of minutes. When the time is up, the run() method on the TimerTask is called behind the scenes by Timer, which causes it to play a sound. The application then terminates after the timer is cancelled.

Tutorial Pages:
» Introduction
» Scheduling a one-shot task
» Scheduling a recurring task
» Implementing the scheduling framework
» Extending the cron facility
» Real-time guarantees
» Conclusion
» Resources


First published by IBM developerWorks


 | Bookmark
Related Tutorials:
» All about JAXP, Part 1
» Make Database Queries Without the Database
» Load List Values for Improved Efficiency
» 2 Ways To Implement Session Tracking
» A Simple Way to Read an XML File in Java
» Develop Aspect-Oriented Java Applications with Eclipse and AJDT