Sunday, February 14, 2016

Java Timer Example

Java Timer Example:

Think of a scenario where I want my code to execute at a particular time in my application or at sometime later from the current time. In other words, I want to schedule my task at the definite time. How can this be possible using Java Programming language?

Tutorial:

Java Timer class (java.util.Timer) allows an application to schedule the task on a separate background thread. Please note that by default the associated thread is a non-daemon thread i.e. application does not terminate pending timer thread to complete execution.However, you can change the associated thread to Timer Class as Daemon Thread during creation of Timer Object. (Learn more about Daemon Thread in java)

Timer Task:

Timer class needs Timer Task (java.util.TimerTask) (Runnable Object) to execute the task. This is the class where the actual logic implementation resides inside run method. Timer when scheduled, picks up Timer Task and executes (once or repetitive as the case may be).

How to schedule Task:

Timer class provides various ways to schedule the task based on number of execution and rate of execution. Here are the list:

Method Signature

Purpose

schedule (TimerTask task, Date time)  Schedule task at specified Date time. It will be executed only once on the time specified
schedule (TimerTask task, Date firstTime, long period)  Schedule task at specified Date time. It will start executing from the specified date time and then repeat after the period specified henceforth
schedule (TimerTask task, long delay) Schedule task after delay time. It will be executed only once on the delay time specified from the current time
schedule (TimerTask task, long delay, long period) Schedule task after delay time with fixed delay period time unit execution thereafter. 
scheduleAtFixedRate (TimerTask task, Date firstTime, long period) Schedule task at specified Date time with fixed rate execution. It will start executing from the specified date time and then repeat after the period specified henceforth. If the task couldn't start at the specified time, the next task will get triggered before the period time to adjust the fixed rate. 
scheduleAtFixedRate (TimerTask task, long delay, long period Schedule task after delay time with fixed rate execution. It will start executing from the specified date time and then repeat after the period specified henceforth. If the task couldn't start at the specified time, the next task will get triggered before the period time to adjust the fixed rate. 


How Java Timer works internally:

Internally Timer uses binary heap data structure to store Timer tasks. The constructor to create Timer object also creates Timer Thread with it and schedule method put the task on binary heap. It works on Object.wait() call to maintain Thread wait and notify.
Timer class is also thread-safe so multiple threads can simultaneously use it.

Java Timer Code Example :

import java.util.Timer;
import java.util.TimerTask;
public class JavaTimer {
  public static void main(String[] args){
  Timer timer = new Timer();
  TimerTask task = new TimerTask() {
      @Override
   public void run() {
    System.out.println("Inside Timer Task" + System.currentTimeMillis());
       }
  };
  System.out.println("Current time" + System.currentTimeMillis());
  timer.schedule(task, 10000,1000);
  System.out.println("Current time" + System.currentTimeMillis());
   }
}

Output :

Current time1455469505220
Current time1455469505221
Inside Timer Task1455469515222
Inside Timer Task1455469516222
Inside Timer Task1455469517222
Inside Timer Task1455469518222
Inside Timer Task1455469519222
Inside Timer Task1455469520222
Inside Timer Task1455469521222
Inside Timer Task1455469522222
Inside Timer Task1455469523222
Inside Timer Task1455469524222
Inside Timer Task1455469525222
Inside Timer Task1455469526222
Inside Timer Task1455469527222
Inside Timer Task1455469528223
Inside Timer Task1455469529223 and it goes on

Analysis :

The call to timer.schedule(task, 10000,1000) is going to schedule the task which is going to execute for first time (on another thread) after 10 second from this call. After that it will call again after delay of 10 seconds. It is important to mention here that if the task cannot be started after 10 seconds, next task call will not get pre-pond. So here the delay time between two consecutive task is fixed.

How to cancel Timer Thread:

To cancel and discard all scheduled task from the queue, cancel() method needs to be called. If there is any on-going execution, it will not interrupt in between. Rather it cancels all other scheduled task from the queue and after completion of on-going task(if any), Timer thread exits gracefully.

How to cancel already running Task:

To cancel already running task, you need to identify check points where you need to cancel the task. Take AtomicInteger as signal to cancel task and change its value inside cancel() method and when cancel signal comes then inside your task there are various check points which will check the value  and exit the task (Please remember to do cleanup/rollback as needed before existing the task thread).

No comments:

Post a Comment