Java Reference
In-Depth Information
Scheduling Tasks
The TimerDemo program demonstrates scheduling a repeated task. The run()
method of the GCTask object is invoked every 5 seconds. You can also sched-
ule a task for a single execution, which is scheduled at a specific time or after a
specified delay.
Repeating tasks are assigned a period that denotes the time between execu-
tions, and they fit into two categories:
Fixed-delay execution. The period is the amount of time between the
ending of the previous execution and the beginning of the next execution.
Fixed-rate execution. The period is the amount of time between the start-
ing of the previous execution and the beginning of the next execution.
For example, the GCTask task in the TimerDemo program is a fixed-delay
task with a period of 5 seconds, which means that the 5-second period starts
after the current task ends. Compare this to a fixed-rate execution with a
period of 5 seconds. The fixed-rate task is scheduled every 5 seconds, no mat-
ter how long the previous task takes to execute. If the previously scheduled
task has not finished yet, subsequent tasks will execute in rapid succession.
Fixed-rate scheduling is ideal when you have a task that is time-sensitive, such
as a reminder application or clock.
Each schedule() method can throw an IllegalStateException if the task has
already been scheduled. A TaskTimer object can be scheduled only once.
If you need to repeat a task, you need to schedule a new instance of your
TimerTask class.
The java.util.Timer class contains the following methods for scheduling a
TimerTask:
public void schedule(TimerTask task, Date time). Schedules a task for a
single execution at the time specified. If the time has already past, the
task will be scheduled immediately. If the task has already been sched-
uled, an IllegalStateException is thrown.
public void schedule(TimerTask task, long delay). Schedules a task for
a single execution after the specified delay has elapsed.
public void schedule(TimerTask task, long delay, long period). Sched-
ules a task for fixed-delay execution. The delay parameter represents the
amount of time to wait until the first execution, which can be different
from the period it is scheduled to run.
Search WWH ::




Custom Search