THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

22.7. Timer and TimerTask


The Timer class helps you set up tasks that will happen at some future point, including repeating events.
Each Timer object has an associated thread that wakes up when one of its TimerTask objects is destined to
run. For example, the following code will set up a task that prints the virtual machine's memory usage
approximately once a second:


Timer timer = new Timer(true);
timer.scheduleAtFixedRate(new MemoryWatchTask(), 0, 1000);


This code creates a new Timer object that will be responsible for scheduling and executing a
MemoryWatchTask (which you will see shortly). The TRue passed to the Timer constructor tells Timer
to use a daemon thread (see page 369) so that the memory tracing activity will not keep the virtual machine
alive when other threads are complete.


The scheduleAtFixedRate invocation shown tells timer to schedule the task starting with no delay
(the 0 that is the second argument) and repeat it every thousand milliseconds (the 1000 that is the third
argument). So starting immediately, timer will invoke the run method of a MemoryWatchTask:


import java.util.TimerTask;
import java.util.Date;


public class MemoryWatchTask extends TimerTask {
public void run() {
System.out.print(new Date() + ": " );
Runtime rt = Runtime.getRuntime();
System.out.print(rt.freeMemory() + " free, ");
System.out.print(rt.totalMemory() + " total");
System.out.println();
}
}


MemoryWatchTask extends the abstract TimerTask to define a task that prints the current free and total
memory, prefixed by the current time. TimerTask implements the Runnable interface, and its run
method is what is invoked by a Timer object when a task is to be run. Because the setup code told timer to
execute once a second, the thread used by timer will wait one second between task executions.


TimerTask has three methods:


public abstract voidrun()

Defines the action to be performed by this TimerTask.

public booleancancel()

Cancels this TimerTask so that it will never run again (or at all if it hasn't
run yet). Returns true if the task was scheduled for repeated execution or
was a once-only task that had not yet been run. Returns false if the task
was a once-only task that has already run, the task was never scheduled, or
the task has previously been cancelled. Essentially, this method returns true
if it prevented the task from having a scheduled execution.
Free download pdf