Java Reference
In-Depth Information
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 schedul-
ing and executing a
MemoryWatchTask
(which you will see shortly). The
TRue
passed to the
Timer
constructor tells
Timer
to use a daemon thread (see
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 re-
peat it every thousand milliseconds (the
1000
that is the third argu-
ment). 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();
}
}