Java Reference
In-Depth Information
public void schedule(TimerTask task, Date firstTime, long period).
Schedules a task for fixed-delay execution. The Date parameter repre-
sents the time of the first execution.
public void scheduleAtFixedRate(TimerTask task, long delay, long
period). Schedules a task for fixed-rate execution. The delay parameter
represents the amount of time to wait until the first execution, which can
be different from the period during which it runs.
public void scheduleAtFixedRate(TimerTask task, Date firstTime, long
period). Schedules a task for fixed-rate execution. The Date parameter
represents the time of the first execution.
Notice that each schedule() method takes in either a start time or a delay
time (the amount of the time before the first scheduled execution). Also, each
method has a TimerTask parameter to represent the code that runs when the
task is scheduled. The TimerTask class has three methods in it:
public abstract void run(). The method invoked by the Timer. Notice that
this method is abstract and therefore must be overridden in the child
class.
public boolean cancel(). Cancels the task so that it will never run again.
If the task is currently running, its current execution will finish. The
method returns true if an upcoming scheduled task was canceled.
public long scheduledExecutionTime(). Returns the time at which the
most recent execution of the task was scheduled to occur. This method is
useful for fixed-delay tasks, whose scheduled times vary.
For example, the following if statement checks to see whether an execu-
tion of the previous task took longer than three seconds. If it did, this execution
will voluntarily skip its turn to run by simply returning from the run()
method.
if(System.currentTimeMillis() - this.scheduledExecutionTime() >= 3000)
{
System.out.println(“Previous execution took too long”);
return;
}
To demonstrate a fixed-rate execution, the following Phone class uses a
PhoneRinger task to simulate the ringing of a telephone, with a 3-second
period. Study the code of these two classes and try to determine what the out-
put of main() is, which is shown in Figure 15.7.
Search WWH ::




Custom Search