Java Timer example

Timer is an utility class which can be used to schedule tasks on specific time or repeatedly.
Lets say, you are developing an banking application and there is need to process the data at 7 PM evening daily. You can easily schedule task using Timer class.

For creating a task, you need to extends TimerTask and Timer can be used to set time for the task.

TimerTask : It is task which will be executed at specific time.
Timer : It is utility class which is used to set time for the task.

Timer class is thread safe , so multiple threads can share one timer object. Timer class internally uses java.util.TaskQueue to manage task internally. Only one thread can execute timer task at a time.


For example:
You are executing task in every 5 secs but actual execution itself is taking 10 seconds, then subsequent task will be added to queue and as soon as current execution completes, it will notify and another thread will start executing the task.
When you debug timer object, it looks something like this.
Java timer example

Methods for scheduling task:

There are several methods in timer class that can be used to schedule.

For one time execution:
public void schedule(TimerTask task, long delay,long period)
For example:
// it will execute timer task after delay of 5 seconds
timer.schedule(new MyTimerTask(),5000);

For repeated execution:
public void schedule(TimerTask task,long delay)
For example:
// it will execute timer task in every 2 seconds after first delay of 1 second
timer.schedule(new MyTimerTask(),1000,2000);

For executing task at particular time:
public void schedule(TimerTask task, Date time)
For example:
  // Scheduling task at today : 23:13:00 PM
  Calendar calendar = Calendar.getInstance();
  calendar.set(Calendar.HOUR_OF_DAY, 23);
  calendar.set(Calendar.MINUTE, 13);
  calendar.set(Calendar.SECOND, 0);
  Date time = calendar.getTime();

  timer.schedule(new MyTimerTask(timer), time);

For executing task at particular time repeatedly:
public void schedule(TimerTask task, Date firstTime, long period)

Example:

For one time exectution:

Create a class MyTimerTask.java
package org.arpit.java2blog.timer;

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

public class MyTimerTask extends TimerTask{
 
 Timer timer;
 public MyTimerTask(Timer timer) {
  this.timer=timer;
 }

 @Override
 public void run() {
  System.out.println("Executing timer task");
  // to stop timer thread
  timer.cancel();
  
 }

}
In above class, we are using timer.cancel() to stop the timer thread. When you call timer.cancel() method, it completes execution of current thread and discards all other threads which are in queue.

Create a class TimerMain.java.
package org.arpit.java2blog.timer;

import java.util.Timer;

public class TimerMain {

 public static void main(String[] args) {
  // It will create new thread
  Timer timer=new Timer();
  //  task will be scheduled after 5 sec delay
  timer.schedule(new MyTimerTask(timer), 5000);
 

 }

}
When you run above program, you will get following output:
Executing timer task

For repeated execution:

Create a class MyTimerTask.java
package org.arpit.java2blog.timer;

import java.util.TimerTask;

public class MyTimerTask extends TimerTask{

 @Override
 public void run() {  
  System.out.println("Executing timer task on "+TimerMain.convertTimeToDateFormat(System.currentTimeMillis()));
 }

}

Create a class TimerMain.java.
package org.arpit.java2blog.timer;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;

public class TimerMain {

 public static void main(String[] args) {
  System.out.println("Timer tasks started on "+convertTimeToDateFormat(System.currentTimeMillis()));
  System.out.println("**************************");
  // It will create new thread
  Timer timer=new Timer();

  timer.schedule(new MyTimerTask(), 1000,2000);

  // Stopping the timer thread after some time for example :12 secs.

  try {
   Thread.sleep(12000);
  } catch (InterruptedException e) {

   e.printStackTrace();
  }

  // you can call timer.cancel() or System.exit(0)
  System.out.println("**************************");
  System.out.println("Timer tasks finished on "+convertTimeToDateFormat(System.currentTimeMillis()));

  System.exit(0);
 }

 public static String convertTimeToDateFormat(long milliseconds)
 {
  SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm:ss");    
  Date resultdate = new Date(milliseconds);
  return sdf.format(resultdate);
 }

}
When you run above program, you will get following output:
Timer tasks started on Aug 18,2015 22:48:22
**************************
Executing timer task on Aug 18,2015 22:48:23
Executing timer task on Aug 18,2015 22:48:25
Executing timer task on Aug 18,2015 22:48:27
Executing timer task on Aug 18,2015 22:48:29
Executing timer task on Aug 18,2015 22:48:31
Executing timer task on Aug 18,2015 22:48:33
**************************
Timer tasks finished on Aug 18,2015 22:48:34

For executing task at particular time:

Create a class MyTimerTask.java
package org.arpit.java2blog.timer;

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

public class MyTimerTask extends TimerTask{

 Timer timer;

 MyTimerTask(Timer timer)
 {
  this.timer=timer;
 }
 @Override
 public void run() {  
  System.out.println("Executing timer task on "+TimerMain.convertTimeToDateFormat(System.currentTimeMillis()));
  // to stop time thread
  timer.cancel();
 }

}

Create a class TimerMain.java.

package org.arpit.java2blog.timer;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

public class TimerMain {

 public static void main(String[] args) {
  System.out.println("Timer tasks started on "+convertTimeToDateFormat(System.currentTimeMillis()));
  System.out.println("**************************");
  // It will create new thread
  Timer timer=new Timer();

  // Scheduling task at today : 23:13:00 PM
  Calendar calendar = Calendar.getInstance();
  calendar.set(Calendar.HOUR_OF_DAY, 23);
  calendar.set(Calendar.MINUTE, 13);
  calendar.set(Calendar.SECOND, 0);
  Date time = calendar.getTime();

  timer.schedule(new MyTimerTask(timer), time);

 }

 public static String convertTimeToDateFormat(long milliseconds)
 {
  SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm:ss");    
  Date resultdate = new Date(milliseconds);
  return sdf.format(resultdate);
 }

}

When you run above program, you will get following output:
Timer tasks started on Aug 18,2015 23:12:40
**************************
Executing timer task on Aug 18,2015 23:13:00

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012