How to use timer in Java


Java Schedule Timer TimerTaskViews 2778

Java Timer class executes a task or job in a specific time interval either once or repeatedly. It is part of the Java utility class. This class is also used to schedule jobs on a specified date using its in-built methods.

If we want to create our own task, we have to extend the TimerTask class which is an abstract class. The timer class uses this task for scheduling. In other words, Timer is used as a scheduler and TimerTask is the job that needs to be scheduled.

Java Timer Constructors

We can create Timer object using the below constructors

ConstructorDescription
Timer()This is the default timer
Timer(boolean isDaemon)This creates a timer with its associated thread to run as a daemon
Timer(String name)This creates a timer with its associated thread with the specified name
Timer(String name, boolean isDaemon)This creates a timer with its associated thread with specified name and can be run as a daemon
Timer t = new Timer();

Java Timer Methods

Below are the most commonly used Java Timer methods.

MethodDescriptionParameters
void cancel()Terminates the timer. It cancels all the scheduled tasks except the current running task if any
int purge()This removes all the cancelled tasks from the queue and returns the number of tasks removed.
void schedule(TimerTask task, Date time)Schedules the specified task to run at the specified time. If the time is past, then it is immediately taken for executiontask - task to be performed
time - time at which task has to be performed
void schedule(TimerTask task,long delay)Schedules a specified task after the specified delaytask - task to be performed
delay - delay in milliseconds before task execution
void schedule(TimerTask task, Date firsttime, long period)Schedules a specific task on the specific start for repeated execution with the mentioned periodic intervaltask - task to be performed
firstime - start time of the task for the execution
period - interval with which task has to be executed
void schedule(TimerTask task, long delay, long period)Schedules a specific task for repeated execution after the specified delay with the mentioned periodic intervaltask - task to be performed
delay - delay in milliseconds before task execution
period - interval with which task has to be executed
vois scheduleAtFixedRate(TimerTask task, Date firsttime, long period)Schedules a specific task with fixed rate execution starting with the specific date with the mentioned periodic intervalstask - task to be performed
firstime - start time of the task for the execution
period - interval with which task has to be executed
void scheduleAtFixedRate(TimerTask task,long delay,long period)Schedules a specific task for repeated fixed rate execution after the specified delay with the mentioned periodic intervaltask - task to be performed
delay - delay in milliseconds before task execution
period - interval with which task has to be executed

Timer Exceptions

The Java Timer class throws the below exceptions while scheduling tasks:

  • NullPointerException – when the task or time is null
  • IllegalArgumentException – when the time or delay or period is negative
  • IllegalStateException – if the task was already scheduled or canceled, the timer was canceled or timer thread was terminated

Java Timer: Schedule a task using schedule(task, time)

Let’s see a simple example of scheduling a task using a java timer at a specified time. First, we create a new timer object ‘t’. Then, we create a TimerTask object “task” and provide the required code by overriding the run method. We then schedule the task using the timer at the specified time(here, current time).

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerDemo {

  public static void main(String[] args) {
    Timer t = new Timer();
    TimerTask task = new TimerTask(){
      public void run()
      {
        for(int i=1;i<=5;i++) {
          System.out.println("Task : " + i);
        }
      }
      
    };
    
    t.schedule(task, new Date());
  }

}
Task : 1
Task : 2
Task : 3
Task : 4
Task : 5

Java Timer: Schedule a task using schedule(task, delay)

In the below example, we are scheduling the task for execution after a delay of 5 seconds. If you see the output, you can clearly see that the Java Timer executed the task after a delay of 5 seconds.

import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;

public class TimeDemoDelay {

  public static void main(String[] args) {
    Timer t = new Timer();
    TimerTask task = new TimerTask() {
      public void run()
      {
        System.out.println("Timer executed at time: "+ new Date());
      }
    };
    System.out.println("Current time: " + new Date());
    t.schedule(task, 5000);
  }

}
Current time: Sat Jun 27 16:01:03 IST 2020
Timer executed at time: Sat Jun 27 16:01:08 IST 2020

Java Timer: Schedule a task using schedule(task, time, period)

In the below example we can see that we can schedule a task for repeated execution at regular time intervals beginning at the specified time.

Here, the Java Timer executes the task starting from the current time and continues its execution after every 2 seconds. Since we want to cancel the task after a specific time, we call cancel method based on a certain condition, else it will continuously execute. In our example, we have set the condition until i=5. Once it reaches this limit, the Java Timer will cancel the task and stop the execution.

import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;

public class TimerDemo1 {

  public static void main(String[] args) {
    Timer t = new Timer();
    TimerTask task = new TimerTask() {
      int i=1;
      public void run() {
        System.out.println("Timer executed at :" + new Date());
        if(i==5)
          t.cancel();
        i=i+1;
      }
    };
    
    System.out.println("Current time: " + new Date());
    t.schedule(task, new Date(), 2000);
  }

}
Current time: Sat Jun 27 16:13:33 IST 2020
Timer executed at :Sat Jun 27 16:13:33 IST 2020
Timer executed at :Sat Jun 27 16:13:35 IST 2020
Timer executed at :Sat Jun 27 16:13:37 IST 2020
Timer executed at :Sat Jun 27 16:13:39 IST 2020
Timer executed at :Sat Jun 27 16:13:41 IST 2020

Java Timer: Schedule a task  using schedule(task, delay, period)

In the below example, we schedule a task for repeated execution after a specific delay(which is 5 seconds) and the Java Timer executes this task in a specific time interval. Even though the time interval is 1 second, the thread executes after every 2 seconds due to another thread that sleeps for 2 seconds. Hence, if you see only the 1st task executes with a delay of a total of 3 seconds, remaining executes every 2 seconds.

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerDelayPeriod {

  public static void main(String[] args) {
    Timer t = new Timer();
    TimerTask task = new TimerTask() {
      int i=1;
      public void run() {
        System.out.println("Timer executed at :" + new Date());
        try {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        if(i==5)
          t.cancel();
        i=i+1;
      }
    };
    
    System.out.println("Current time: " + new Date());
    t.schedule(task, 5000, 1000);

  }

}
Current time: Sun Jun 28 20:04:37 IST 2020
Timer executed at :Sun Jun 28 20:04:42 IST 2020
Timer executed at :Sun Jun 28 20:04:44 IST 2020
Timer executed at :Sun Jun 28 20:04:46 IST 2020
Timer executed at :Sun Jun 28 20:04:48 IST 2020
Timer executed at :Sun Jun 28 20:04:50 IST 2020

Schedule a task using scheduleAtFixedRate(task,time,period)

This method is useful when we want repeated execution at a fixed rate with a periodic interval starting from a particular time. In the below example, we can see that the task execution interval is 1 second, but the Java Timer executes the task every 3 seconds due to another thread that sleeps for 3 seconds. Since this 1 second covers within the 3 seconds limit, it does not wait for another extra 1 second and starts the next task execution immediately.

import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;
public class TimerFixedRateDemo {

  public static void main(String[] args) {
    Timer t = new Timer();
    TimerTask task = new TimerTask() {
      int i=1;
      public void run()
      {
        System.out.println("Task executed at time: " + new Date());
        try {
          Thread.sleep(3000);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        if(i==5)
          t.cancel();
        i=i+1;
      }
    };
    t.scheduleAtFixedRate(task, new Date(), 1000);
  }

}
Task executed at time: Sun Jun 28 22:54:00 IST 2020
Task executed at time: Sun Jun 28 22:54:03 IST 2020
Task executed at time: Sun Jun 28 22:54:06 IST 2020
Task executed at time: Sun Jun 28 22:54:09 IST 2020
Task executed at time: Sun Jun 28 22:54:12 IST 2020

Schedule a task using scheduleAtFixedRate(task,delay,period)

Here, we start the task execution after a delay of 2 seconds with a periodic interval of 1 second. The Java Timer executes the task for a period of 3 seconds due to another thread execution which sleeps for 3 seconds. Since the interval of 1-second covers within this sleep limit, next thread execution starts immediately without any delay.

import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;
public class TimerFixedRateDemo {

  public static void main(String[] args) {
    Timer t = new Timer();
    TimerTask task = new TimerTask() {
      int i=1;
      public void run()
      {
        System.out.println("Task executed at time: " + new Date());
        try {
          Thread.sleep(3000);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        if(i==5)
          t.cancel();
        i=i+1;
      }
    };
    System.out.println("Current time: " + new Date());
    t.scheduleAtFixedRate(task, 2000, 1000);
  }

}
Current time: Sun Jun 28 22:55:59 IST 2020
Task executed at time: Sun Jun 28 22:56:01 IST 2020
Task executed at time: Sun Jun 28 22:56:04 IST 2020
Task executed at time: Sun Jun 28 22:56:07 IST 2020
Task executed at time: Sun Jun 28 22:56:10 IST 2020
Task executed at time: Sun Jun 28 22:56:13 IST 2020

Java Timer

Creating own Java TimerTask Class

We can create our own TimerTask class by extending the abstract class TimerTask as shown in the below example. Every TimerTask abstract class has a run method that we need to override to perform any operation. In the below example, the Java Timer executes the task every second and after 5 seconds, the task execution cancels and stops.

import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;


public class TimerTaskDemo extends TimerTask {
  public void run() {
    System.out.println("Executing task from my own timer task class");
  }
  public static void main(String[] args) throws InterruptedException {
    Timer t = new Timer();
    TimerTask task = new TimerTaskDemo();
    
    t.schedule(task, new Date(),1000);
    Thread.sleep(5000);
    t.cancel();
    System.out.println("Timer cancelled");
  }
  

}
Executing task from my own timer task class
Executing task from my own timer task class
Executing task from my own timer task class
Executing task from my own timer task class
Executing task from my own timer task class
Timer cancelled

Reference

Translate »