Timer TimerTask Java


Timer TimerTask Java Introduction

The classes, Timer and TimerTask from java.util package, introduced with JDK 1.3, are used with threads to animate the images at regular intervals of time. If the stipulated (delay) period of time is over, the Timer object can generate events. Simply by handling the event, the programmer can execute some user-defined method at specified intervals of time to perform a job. The Timer class and TimerTask classes come together in programming. A TimerTask object represents a job (task). The task can be called by the Timer any number of times at regular intervals.

Threads can be assigned for different tasks. A task can perform a job only once or a number of times repeatedly at specified intervals. Timer class is capable to schedule the threads. Infact, each Timer object is represented by a thread at the background. This thread is instrumental to take care of the tasks of the timer.

The TimerTask is an abstract class and implements Runnable interface. So, as Runnable interface is implemented, we must override run() method when TimerTask is extended.

Following program illustrates the usage of Timer and TimerTask classes.

import java.util.*;
class MyTask extends TimerTask
{
  int counter = 1;
  public void run()
  {
    System.out.println(counter++ + " times  the Timer is executed so far");
  }
}
public class TandT
{
  public static void main(String args[])
  {
    MyTask mt1 = new MyTask();
    Timer t1 = new Timer();
    t1.schedule(mt1, 2000, 5000);

    try
    {
      Thread.sleep(21000);
    }
    catch(InterruptedException e)
    {
      e.printStackTrace();
    }
    t1.cancel();
  }
}


Timer TimerTask Java
Output screenshot on Timer TimerTask Java

t1.schedule(mt1, 2000, 5000);

Here, the Timer object, t1, calls first time after 2000 milliseconds and subsequently for every 5000 milliseconds in a period of 21000 milliseconds. It calls three times (21000-2000)/5000). Total it calls 4 times, including the first call after 2000 milliseconds.

mt1 is the object of MyTask that implements TimerTask . The Timer object, t1, schedules the task. 2000 milliseconds is known as delay period and 5000 milliseconds is called as fixed period.

The schedule() method of Timer schedules (or calls) the run() method for every 5000 milliseconds.

t1.cancel( );

The cancel() terminates the Timer thread and thereby all the tasks of Timer thread are discarded.

Leave a Comment

Your email address will not be published.