Java Timer

Introduction

Java Timer and TimerTask are part of the java.util package.These classes can be used to schedule jobs or tasks in the background threads.

 

1. Java Timer 

Java Timer and TimeTask work in conjunction.Timer class can be used to schedule tasks for one-time execution or can be used for repeated execution at regular interval.

To put it in simple words, TimeTask is the task and Timer is the trigger for this.

 

2. Java Timer Example

There are numbers of interesting features with Java Timer class.

  • Timer class is thread safe and multiple threads can use it.
  • Multiple threads can share single Timer instance.
  • It uses binary heap map internally for tasks queue hence it can be easily scaled to a large number of concurrently scheduled tasks. 

 

 

2.1 One Time Job Schedule

let’s create an example of running a single task using Timer.

public class OneTimeSchedulerExample {

    public static void main(String[] args) {

        Timer timer = new Timer("One Time Timer Test");
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Execution time is :" + System.currentTimeMillis() + " Name of the thread is :" + Thread.currentThread().getName());
            }
        };

        timer.schedule(task, 1000L);
    }

}

2.2 Schedule Repeated Tasks

In this example, let’s create tasks to run at the predefined interval.

public class RepeatedScheduleTimerExample {

    public static void main(String[] args) {
        Timer timer = new Timer("Repeated Interval");
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Execution time is :" + System.currentTimeMillis() + " Name of the thread is :" + Thread.currentThread().getName());
            }
        };

        long duration = 1500L;
        long delay= 1000L;
        timer.schedule(task, delay,duration);
    }
}

output

There are few interesting points to discuss for the repeated tasks interval schedule.

  • The scheduleAtFixedRate method takes 3 parameters
    • a task for scheduling.
    • delay in milliseconds before task execution.
    • time in milliseconds between successive task executions.
  • In case execution delay for any reason (e.g background activities or Garbage collector), two or more executions will occur in rapid succession to * “catch up.”

Use duration parameter to schedule tasks based on your need (e.g. schedule tasks once a day duration=1000*60*60*24

 

 

3. Cancel Timer

To cancel Java timer, we can use cancel() method on the timer object.Here is the rule of thumb for this

  • Use cancel() method on the timer if it’s the only method.
  • Perform cancel() on Java TimeTask if multiple tasks executed by the timer and we want to cancel the specific task.
public class CancelTimerExample {

    public static void main(String[] args) throws InterruptedException {
        Timer timer = new Timer("cancel Timer");
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Execution time is :" + System.currentTimeMillis() + " Name of the thread is :" + Thread.currentThread().getName());
            }
        };

        long duration = 1500L;
        long delay= 1000L;
        timer.scheduleAtFixedRate(task, delay,duration);
        Thread.sleep(1000 * 1);
        task.cancel();
        timer.cancel();
    }
}

 

Summary

In this post, we discussed how to use Java Timer and TimerTask to schedule tasks based on our requirement. We covered Java Timer Example for one time and repeated schedule.

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of