Timer and TimerTask

In this chapter you will learn:

  1. What is a Timer
  2. Set up a timer
  3. How to cancel a timer
  4. Schedule a task that executes once every second

What is a Timer

Timer schedules a task for execution at some future time. Timer and TimerTask do the scheduling.

Using Timer, you can create a thread that runs in the background, waiting for a specific time. When the time arrives, the task linked to that thread is executed.

You can schedule a task for repeated execution. Or you can schedule a task to run on a specific date.

Timer is the class that you will use to schedule a task for execution. The scheduled task is an instance of TimerTask.

TimerTask implements the Runnable interface.

Methods from TimerTask

  • boolean cancel()Terminates the task. Returns true if an execution of the task is prevented. Otherwise, returns false.
  • abstract void run()Contains the code for the timer task.
  • long scheduledExecutionTime()Returns the time at which the last execution of the task was scheduled to have occurred.

Once a task has been created, it is scheduled for execution by an object of type Timer.

The constructors for Timer are shown here:

  • Timer()creates a Timer object that runs as a normal thread.
  • Timer(boolean DThread)uses a daemon thread if DThread is true. A daemon thread will execute only as long as the rest of the program continues to execute.
  • Timer(String tName)specify a name for the Timer thread.
  • Timer(String tName, boolean DThread)specify a name for the Timer thread and if to use the daemon thread.

Once a Timer has been created, you will schedule a task by calling schedule() on the Timer that you created.

If you create a non-daemon task, then you will want to call cancel() to end the task when your program ends.

Methods from Timer class

  • void cancel()
    Cancels the timer thread.
  • int purge()
    Deletes cancelled tasks from the timer's queue.
  • void schedule(TimerTask TTask, long milliseconds)
    TTask is scheduled for execution after the period passed in wait has elapsed.
  • void schedule(TimerTask TTask, long waitInMilliseconds, long repeatInMilliseconds)
    TTask is scheduled for execution after the period passed in wait has elapsed. The task is then executed repeatedly at the interval specified by repeat.
  • void schedule(TimerTask TTask, Date targetTime)
    TTask is scheduled for execution at the time specified by targetTime.
  • void schedule(TimerTask TTask, Date targetTime, long repeatInMilliseconds)
    TTask is scheduled for execution at the time specified by targetTime. The task is then executed repeatedly at the interval passed in repeat.
  • void scheduleAtFixedRate( TimerTask TTask, long wait, long repeat)
    TTask is scheduled for execution after the period passed in wait has elapsed.
  • void scheduleAtFixedRate( TimerTask TTask, Date targetTime, long repeat)
    TTask is scheduled for execution at the time specified by targetTime. The task is executed repeatedly at the interval passed in repeat. The repeat parameter is specified in milliseconds.

Set up a timer

The following code sets up a timer with an initial delay of 1 second, then repeat every half second.

import java.util.Timer;
import java.util.TimerTask;
/*j  ava  2  s . c o m*/
class MyTimerTask extends TimerTask {
  public void run() {
    System.out.println("Timer task executed.");
  }
}

public class MainClass {
  public static void main(String args[]) {
    MyTimerTask myTask = new MyTimerTask();
    Timer myTimer = new Timer();

    /*
     * Set an initial delay of 1 second, then repeat every half second.
     */
    myTimer.schedule(myTask, 1000, 500);

    try {
      Thread.sleep(5000);
    } catch (InterruptedException exc) {
    }

    myTimer.cancel();
  }
}

The code above generates the following result.

Cancel a timer

The following code calls cancel() method to terminate a timer thread.

import java.util.Timer;
import java.util.TimerTask;
//j  a  v  a 2 s .  c  om
public class Main {
  Timer timer;

  public Main(int seconds) {
    timer = new Timer();
    timer.schedule(new RemindTask(), seconds * 1000);
  }

  class RemindTask extends TimerTask {
    public void run() {
      System.out.println("Time's up!");
      timer.cancel(); //Terminate the timer thread
    }
  }

  public static void main(String args[]) {
    System.out.println("About to schedule task.");
    new Main(5);
    System.out.println("Task scheduled.");
  }
}

The code above generates the following result.

Schedule a task that executes once every second

The following code uses scheduleAtFixedRate(TimerTask task, long delay, long period) to schedule a task that executes once every second.

import java.awt.Toolkit; import java.util.Timer; import java.util.TimerTask;
public class Main {
  Toolkit toolkit;//j  av  a2  s .  c o m

  Timer timer;

  public Main() {
    toolkit = Toolkit.getDefaultToolkit();
    timer = new Timer();
    timer.scheduleAtFixedRate(new RemindTask(), 0, //initial delay
        1 * 1000); //subsequent rate
  }

  class RemindTask extends TimerTask {
    int numWarningBeeps = 3;

    public void run() {
      if (numWarningBeeps-- > 0) {
        long time = System.currentTimeMillis();
        if (time - scheduledExecutionTime() > 5) {
          return;
        }
        toolkit.beep();
        System.out.println("Beep!");
      } else {
        toolkit.beep();
        System.out.println("Time's up!");
        System.exit(0);
      }
    }
  }

  public static void main(String args[]) {
    new Main();
  }
}

Next chapter...

What you will learn in the next chapter:

  1. What is DOM
Home » Java Tutorial » Utility Classes
Java standard stream
Java system property get and set
Current time in millis second and nano second
Random UUID
JVM memory
JVM garbage collector
JVM shutting down
Processor count
OS system commands
Random class
Random value
Random value range
Compile Java source code
Timer and TimerTask