Software

Schedule events with the Timer class

Need to programmatically fire off a task at some point in the future? The Java Timer class may be just what you are looking for. Find out about the three types of scheduling you can handle with this useful function.


Scheduling recurrent or future events can be a hassle, but the Timer class can make the job a lot easier. With a couple of simple calls, you can create any number of scheduled or recurring events.

Timers are created with a simple constructor and then called with one of the schedule() methods to set an actual task. Tasks are defined by subclassing the TimerTask class and implementing a run() method that will be called when the scheduled event is reached. TimerTask implementations can be anonymous, as in this example:
java.util.Timer timer = new java.util.Timer();
java.util.TimerTask task = new java.util.TimerTask() {
   public void run() {/*insert task code here*/}
   };


You can create three types of schedules: delay schedules, repeating schedules, and fixed-delay schedules. Delay schedules simply prompt an event to occur once at a specific future time. The code snippet below illustrates a task being scheduled to execute after 10 seconds have elapsed:
timer.schedule(task,10000);

Repeating, or fixed-rate, schedules will prompt events to repeat once per each elapsed period (even if that means that tasks will queue up) and ensure that all events occur as closely as possible to their scheduled times. For example, the following code snippet creates a schedule that will execute its task once for every elapsed second, starting immediately:
timer.scheduleAtFixedRate(task,0,1000);

A fixed-delay timer places the emphasis on ensuring that the indicated delay always elapses between invocations. This example will schedule a task to recur with at least a second delay between invocations, starting immediately:
timer.schedule(task,0,1000);

Each Timer instance runs its tasks in a single thread, so if you want tasks to execute completely independently, you should create a new Timer object for each task. You can assign multiple tasks to a single Timer, but only one task can run at a time. Therefore, multiple timer tasks can delay each other from their scheduled execution times.

Editor's Picks