Home » Core Java » util » Timer » java.util.Timer Example

About Anirudh Bhatnagar

Anirudh is a Java programmer with extensive experience in building Java/J2EE applications. He has always been fascinated by the new technologies and emerging trends in software development. He has been involved in propagating these changes and new technologies in his projects. He is an avid blogger and agile enthusiast who believes in writing clean and well tested code.

java.util.Timer Example

In this example we will see how we can use java.util.Timer class to schedule tasks for future execution in a background thread. The tasks may be scheduled for one-time execution, or for repeated execution at regular intervals. This class is thread safe and multiple threads can share a single Timer object without need for external synchronisation.

For our example we will extend java.util.TimerTask class. This class implements Runnable and is required by the Timer class to schedule the tasks of type TimerTask.

Lets see more details in the example below :

JavaTimerExampleTask.java

package com.jcg.example;

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

public class JavaTimerExampleTask extends TimerTask {

	@Override
	public void run() {
		System.out.println("The execution of task started at: " + new Date());
		// put task implementation here

		// put a sleep
		try {
			Thread.sleep(4000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("The execution of task finished at: " + new Date());

	}

	public static void main(String[] args) {

		TimerTask task = new JavaTimerExampleTask();

		// true means : associated thread should run as a daemon
		Timer timer = new Timer(true);

		// Subsequent executions take place at approximately regular intervals,
		// separated by the specified period.
		timer.schedule(task, 0, 5000);
		System.out.println("The schedular has started");

		try {
			// Putting a sleep of 10000 ms so that the task can run twice as it
			// is scheduled to run every 500ms
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}


In the above example we made an instance of Timer class and made it run as daemon by passing the constructor argument as true. Then we have scheduled the timer to run every 5 second and passed the object of TimerTask by following method :

timer.schedule(task, 0, 5000)

The above method schedules the specified task for repeated fixed-delay execution beginning after the specified delay. (mentioned 0 here )

After running this, we get the following output:

The schedular has started
The execution of task started at: Mon Nov 17 18:31:58 IST 2014
The execution of task finished at: Mon Nov 17 18:32:02 IST 2014
The execution of task started at: Mon Nov 17 18:32:03 IST 2014
The execution of task finished at: Mon Nov 17 18:32:07 IST 2014

The important thing to note here is that the Thread sleep time should be set in such a manner so that the threads can complete the execution. In above example the sleeping time of main thread (10 seconds) allows execution of 2 schedules ( scheduled at every 5 second).

Download the Eclipse project of this tutorial:

So, here we have seen the use of java.util.Timer class to schedule tasks.

Download
You can download the full source code of this example here : javaTimerExample.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

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 ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments