January 2002
Intermediate to advanced
264 pages
8h 3m
English
java.util.TimerTask
TimerTask is an abstract class that acts as the
base class for all scheduled tasks. A task can be scheduled for
one-time or repeated execution by a Timer. To
define a task, create a subclass of TimerTask and
implement the run() method. For example:
import java.util.*;
public class MyTask extends TimerTask {
public void run() {
System.out.println("Run Task");
}
}The run() method is being implemented simply
because the TimerTask implements the
Runnable interface. The run()
method is invoked by the Timer class to run the
task.
After you define a task, you schedule it for execution by creating a
Timer object and invoking the schedule()
method, as shown here:
Timer timer = new Timer(); TimerTask task = new MyTask(); // wait five seconds before executing timer.schedule(task, 5000); // wait two seconds before executing then execute every five seconds timer.schedule(task, 2000, 5000);
Here we are using two of the four versions of the schedule()
method of the Timer class.
public abstract classTimerTaskimplements java.lang.Runnable { // protected constructors protectedTimerTask(); // public instance methods public booleancancel(); public abstract voidrun(); public longscheduledExecutionTime(); }
Read now
Unlock full access