Chapter 18: java.util Part 2: More Utility Classes 523
Once aTimerhas been created, you will schedule a task by callingschedule( )on the
Timerthat you created. As Table 18-9 shows, there are several forms ofschedule( )which
allow you to schedule tasks in a variety of ways.
If you create a non-daemon task, then you will want to callcancel( )to end the task when
your program ends. If you don’t do this, then your program may “hang” for a period of time.
The following program demonstratesTimerandTimerTask. It defines a timer task whose
run( )method displays the message “Timer task executed.” This task is scheduled to run once
every half second after an initial delay of one second.
// Demonstrate Timer and TimerTask.
import java.util.*;
class MyTimerTask extends TimerTask {
Method Description
void cancel( ) Cancels the timer thread.
int purge( ) Deletes cancelled tasks from the timer’s queue.
void schedule(TimerTaskTTask,
longwait)
TTaskis scheduled for execution after the period passed
inwaithas elapsed. Thewaitparameter is specified in
milliseconds.
void schedule(TimerTaskTTask,
longwait, longrepeat)
TTaskis scheduled for execution after the period passed
inwaithas elapsed. The task is then executed repeatedly
at the inter val specified byrepeat.Bothwaitandrepeat
are specified in milliseconds.
void schedule(TimerTaskTTask,
DatetargetTime)
TTaskis scheduled for execution at the time specified
bytargetTime.
void schedule(TimerTaskTTask,
DatetargetTime,
longrepeat)
TTaskis scheduled for execution at the time specified
bytargetTime.The task is then executed repeatedly at
the inter val passed inrepeat. Therepeatparameter is
specified in milliseconds.
void scheduleAtFixedRate(
TimerTaskTTask,
longwait, longrepeat)
TTaskis scheduled for execution after the period passed
inwaithas elapsed. The task is then executed repeatedly
at the inter val specified byrepeat.Bothwaitandrepeat
are specified in milliseconds. The time of each repetition is
relative to the first execution, not the preceding execution.
Thus, the overall rate of execution is fixed.
void scheduleAtFixedRate(
TimerTaskTTask,
DatetargetTime,
longrepeat)
TTaskis scheduled for execution at the time specified
bytargetTime.The task is then executed repeatedly at
the inter val passed inrepeat.Therepeatparameter is
specified in milliseconds. The time of each repetition is
relative to the first execution, not the preceding execution.
Thus, the overall rate of execution is fixed.
TABLE 18-9 The Methods Defined byTimer