Timer

Java Timer example

Photo of Vishal RajpalVishal RajpalJune 16th, 2014Last Updated: June 17th, 2014
0 232 5 minutes read

In this example, we will learn about theTimer class available under thejava.util package.

TheTimer facilitates the execution of tasks in a background thread. The tasks to be executed by theTimer can be chosen either to be a one-time execution OR a repeated execution at pre-defined intervals.

Along with the mentioned execution frequency of the task, the scheduling time / delay of these tasks can also be optionally mentioned to theTimer class.

Representing what is stated above, theTimerTask to be executed can be:

  1. One-time execution which in turn can be:
    • Scheduledimmediately
    • Scheduled to startafter a delay
  2. Repeated execution at regular intervals which in turn can be:
    • Scheduledimmediately
    • Scheduled to startafter a delay

Components of Timer

We would briefly look at the internal components of theTimer class. In terms of usage, one only needs to create Tasks by extending theTimerTask and schedule them with theTimer instance.

The other two internal components –TaskQueue andTimerThread have been mentioned below for information purpose, so as to help one evaluate when and for what kind of tasks should theTimer class be used.

  1. Task Queue

  2. Internally, theTimer uses theTaskQueue as a “priority” queue maintaining tasks in the order of next execution. The priority queue holds task in the sequence they should be executed by theTimerThread.

  3. Timer Thread

  4. TheTimerThread is a thread helper class which repeatedly monitors theTaskQueue and “sequentially” executes the tasks based on their execution order and time of execution. To note here, theTimer has onlyone instance of theTimerThread internally. Thus, if any of the scheduledTimer tasks takes excessive time to run, the other tasks scheduled for execution will keep waiting till the offending task completes. The waiting tasks may then be executed in rapid successions by theTimerThread causing unexpected results.

  5. Timer Task

  6. TheTimerTask is the actual unit of task that needs to be performed by theTimer for either once or multiple times at regular intervals. TheTimerTask is an abstract class implementing Runnable.As a user of theTimer, one needs to extend this class and implement the run method by providing the logic of the task that needs to be performed.

Now, let us look at an example using theTimer. In the example, we create twoTimerTask:

  1. ATimerTask in a slave node which sends some heart-beat information at an interval of 10 seconds. The task is scheduled to start with a delay of 1 second.
  2. ATimerTask which updates the status being sent by the first task to AMBER. This task is executed once after a delay of 30 seconds.

Let’s look atTimerTask #1,TimerTaskSendHeartBeat for heartbeat sending.

class TimerTaskSendHeartBeat extends TimerTask {TimerExample healthStatusHolder = null;public TimerTaskSendHeartBeat(TimerExample healthStatusHolder) {this.healthStatusHolder = healthStatusHolder;}HeartBeatMessage message = null;@Overridepublic void run() {// create HeartBeat message by getting Health Status (RED/GREEN/AMBER)// Error Code, if any AND time at which heartbeat is sent to help// receiver discard any delayed messages due to latencymessage = new HeartBeatMessage(this.healthStatusHolder.getHealthStatus(), Calendar.getInstance().getTimeInMillis(), -1);System.out.println("Sending HeartBeat Message");// Send the message to Monitoring DashboardSystem.out.println(message);System.out.println("HeartBeat Message Sent");}/** * Simple POJO which is a heartbeat message object It can have any decoder * encoder mechanism to send over any messaging platform */class HeartBeatMessage {private String status;private long heartBeatTime;private int errorCode;public HeartBeatMessage(String status, long heartBeatTime, int errorCode) {this.status = status;this.heartBeatTime = heartBeatTime;this.errorCode = errorCode;}public String getStatus() {return status;}public long getHeartBeatTime() {return heartBeatTime;}public int getErrorCode() {return errorCode;}@Overridepublic String toString() {return "status: " + status + " timeOfHeartBeat: "+ new java.util.Date(this.heartBeatTime) + " errCode : "+ this.errorCode;}}

Below is the implementation of theTimerTask # 2,TimerTaskUpdateHeartBeat which just updates the status of the heartbeat message being sent.

class TimerTaskUpdateHeartBeat extends TimerTask {TimerExample healthClass = null;public TimerTaskUpdateHeartBeat(TimerExample healthClass) {this.healthClass = healthClass;}@Overridepublic void run() {System.out.println("Task 2:: 30 seconds completed :: Updating health "+ "status to AMBER");healthClass.setHealthStatus("AMBER");}}

Once both theTimerTask have been created, let us know schedule the tasks at the desired time and frequency of execution. This would require creating a newTimer instance and scheduling tasks to it.

public class TimerExample {private String healthStatus = "GREEN";public static void main(String[] args) {TimerExample example = new TimerExample();example.setHealthStatus("GREEN");// Create the Timer objectTimer timer = new Timer("JCG Timer Example");// Create Timer task created to send heartBeatsTimerTask taskToExecute = new TimerTaskSendHeartBeat(example);// schedule the task to start executing after 1 second// and re-execute every 10 secondstimer.scheduleAtFixedRate(taskToExecute, 1000, 10000);// Create Timer task to setHeartBeatStatusTimerTask setHeartBeatStatus = new TimerTaskUpdateHeartBeat(example);// schedule the task to start immediately but execute// first time after 30 secondstimer.schedule(setHeartBeatStatus, 30000);// Wait for 60 seconds and then cancel the timer cleanlytry {Thread.sleep(60000);} catch (InterruptedException e) {}System.out.println("Cancelling Timer Cleanly after 60 seconds");timer.cancel();}/** * Get Heartbeat Status of the application, could be GREEN / AMBER / RED * based on any exceptions or service health *  * @return String */public String getHealthStatus() {return this.healthStatus;}/** * Set the status for the application could be GREEN / AMBER / RED *  * @param healthStatus */public void setHealthStatus(String healthStatus) {this.healthStatus = healthStatus;}}

On execution of the program, the output looks as below:

Sending HeartBeat Messagestatus: GREEN timeOfHeartBeat: Mon Jun 16 23:52:04 IST 2014 errCode : -1HeartBeat Message SentSending HeartBeat Messagestatus: GREEN timeOfHeartBeat: Mon Jun 16 23:52:14 IST 2014 errCode : -1HeartBeat Message SentSending HeartBeat Messagestatus: GREEN timeOfHeartBeat: Mon Jun 16 23:52:24 IST 2014 errCode : -1HeartBeat Message SentTask 2:: 30 seconds completed :: Updating health status to AMBERSending HeartBeat Messagestatus: AMBER timeOfHeartBeat: Mon Jun 16 23:52:34 IST 2014 errCode : -1HeartBeat Message SentSending HeartBeat Messagestatus: AMBER timeOfHeartBeat: Mon Jun 16 23:52:44 IST 2014 errCode : -1HeartBeat Message SentSending HeartBeat Messagestatus: AMBER timeOfHeartBeat: Mon Jun 16 23:52:54 IST 2014 errCode : -1HeartBeat Message SentCancelling Timer Cleanly after 60 seconds

As seen from output above, theTimer is cancelled using thecancel method which ensures that anyTimerTask being executed is completed before theTimer is cleaned up.

Other Points about Timer

  • TheTimer instance created can be instructed to start theTaskThread as a Daemon Thread, in case the thread should no longer exist if there are no non-daemon threads remaining in the VM.
  • TheTimer is thread-safe and is internally synchronized.
  • Java 5.0 introduced theScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It allows multiple service threads and accepts various time units. Thus, as theTimer has one single task execution thread (highlighted above), theScheduledThreadPoolExecutor can have multiple threads executing/dedicated to task execution, in turn preventing one faulty task causing other tasks to be waiting for thread resource for execution.

Thesource code is available for downloadhere.

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Vishal RajpalVishal RajpalJune 16th, 2014Last Updated: June 17th, 2014
0 232 5 minutes read
Photo of Vishal Rajpal

Vishal Rajpal

Vishal enjoys designing and developing small and mid-sized Enterprise solutions in Java and it's ecosystem. He has graduated from RGTU, India in Electronics and Telecommunication Engineering. Currently, Vishal is working with an Analytics organization, enabling the in-house analytics as well as client teams to use technology as a differentiator for projects / problems related to Big Data.

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.