Name

java.util.TimerTask

Synopsis

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 classTimerTask implements java.lang.Runnable  {
   // protected constructors
   protected TimerTask();
   // public instance methods
   public boolean cancel();
   public abstract void run();
   public long scheduledExecutionTime();
}

Get Wireless Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.