.
Developer Spot - Web Development Tutorials
 


Web Hosting Directory
Budget Web Hosting Linux Web Hosting Small Business Hosting
Windows Web Hosting Reseller Web Hosting Web Hosting Articles

Scheduling Recurring Tasks In Java Applications

By Tom White
2004-01-23
Reader Rating: 5 out of 5
Bookmark Print Version
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.



Article 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


 Rate this article:   Poor          Excellent 


If you found this article interesting, you may want to read these as well:

» Build and Implement A Single Sign-On Solution

» Eye On Performance: A Load Of Stress

» A Brief History Of Garbage Collection



 
Development Tutorials
ASP
CGI & Perl
CSS
HTML
Java
JavaScript
Linux
PHP
XML




More Resources
Web Hosting Articles
Development Tutorials: CGI & Perl - CSS - HTML - Java - JavaScript - Linux - PHP - XML