Wednesday, January 27, 2010

Java Timer for Running Recurrent Housekeeping Tasks

My company has several products which use long running Java programs. Occasionally, these programs need to do some sort of recurrent houskeeping tasks, such as deleting old files or some such task. I've found that the Java Timer class is very helpful for this. First, I create a class that I call a housekeeper to keep the Timer instance and load it with the houskeeping classes needed by the program. The housekeeper looks like this:
package net.tadland.examples.timer;

import java.util.Timer;

public class Housekeeper {

// The task delay is how many milliseconds transpire between the time
// that the task is scheduled and its first run. The task period is
// the time interval between runs.

private static final long TASK1DELAY = 10000;
private static final long TASK1PERIOD = 71 * 60 * 1000; // Run every 71 minutes;
private static final long TASK2DELAY = 60000;
private static final long TASK2PERIOD = 45 * 60 * 1000; // Run every 45 minutes;

private static Housekeeper me = new Housekeeper();

private Timer housekeeperTimer;

private Housekeeper() {

// The boolean parameter here indicates that the timer is
// to be run as a daemon. It will continue running, launching
// each TimerTask specified below, over and over, running
// each TimerTask every period milliseconds.

housekeeperTimer = new Timer("Housekeeper", true);
housekeeperTimer.schedule(new HousekeepingTask1(), TASK1DELAY, TASK1PERIOD);
housekeeperTimer.schedule(new HousekeepingTask2(), TASK2DELAY, TASK2PERIOD);

public static synchronized void stop() {
if (me != null) {
me = null;

Then you will need one or more housekeeping task classes. I create one class per discrete task. A trivial example is:
package net.tadland.examples.timer;

import java.util.TimerTask;

public class HousekeepingTask1 extends TimerTask {

* Since an instance of this class is created once when the daemon
* Housekeeper is created, don't store any transient data in class variables
* in this worker class. Data relative to a given run of this housekeeper
* should be in variables local to the run() method of this class.

public void run() {
// Do your housekeeping tasks here.

There are other ways to use the Timer and TimerTasks, including scheduling tasks to run once at a specific time. The way I've illustrated Timers here is how I've successfully used Timers and TimerTasks to perform recurring houskeeping chores in an unattended system which is deployed at many locations and which runs for months at a time.

No comments:

Post a Comment