Java Timer

Introduction

Java Timer and TimerTask are part of the java.util package. Someone can use these classes to schedule jobs or tasks in the background threads.

 

1. Java Timer 

Java Timer and TimeTask work in partnership. Timer class can schedule tasks for onetime execution or execution at a periodic interval.To put it in simple words, TimeTask is the task and Timer is the trigger for this.

 

2. Java Timer Example

There are lots 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 many concurrently scheduled tasks. 

 

2.1 OneTime Job Schedule

let’s build 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 pre-defined 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();
    }
}

Let’s look at some specific examples:

 

3.1 The TimeTask.cancel() Method

Call the TimeTask.cancel() method to cancel the timer

public static void main(String[] args) throws Exception {
 TimerTask task = new TimerTask() {
  public void run() {
   System.out.println("Executing Task on " + new Date());
   cancel();
  }
 };
 Timer timer = new Timer("TimeTask.cancel()");

 timer.scheduleAtFixedRate(task, 2000 L, 2000 L);

 Thread.sleep(2000 L * 2);
}

 

3.2 The Timer.cancel() Method

Call the Timer.cancel() method on a Timer object:

TimerTask task = new TimerTask() {
  public void run() {
   System.out.println("Executing Task  on " + new Date());
  }
 };
 Timer timer = new Timer("Timer.cancel()");

 timer.scheduleAtFixedRate(task, 2000 L, 2000 L);

 Thread.sleep(1000 L * 2);
 timer.cancel();

 

4. ExecutorService Vs Java Timer

The ExecutorService is powerful and flexible.Here is a basic example to use the ExecutorService:

ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(new Callable() {
  public Object call() throws Exception {
   System.out.println(" ScheduledExecutorServic!");
   return "Called!";
  }
 },
 2,
 TimeUnit.SECONDS);

System.out.println("result = " + scheduledFuture.get());
scheduledExecutorService.shutdown();

Here are guidelines for ExecutorService Vs Java Timer:

  1. Time depends on the system clock while the ExecutorService isn’t.
  2. ExecutorService allow to configure many threads while the Timer has only one execution thread.
  3. ExecutorService can use the available CPU core while the Time can’t.
  4. ThreadPoolExecutor provides better API for management of Thread life cycle.

[pullquote align=”normal”]Use ScheduledThreadExecutor instead of Timer if you can [/pullquote]

 

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.