Byron Kiourtzoglou

About Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Java Timer and TimerTask Example Tutorial

In this tutorial we are going to see how you can use Timer and TimerTask classes of the java.util package in order to schedule the execution of a certain process.

The Timer class uses several flexible methods to make it possible to to schedule a task to be executed at a specific time, for once or for several times with intervals between executions.

To create your own schedulable processes, you have to create your own class the extends TimerTask class. TimerTask implements Runnable interface, so you have to override the run() method.
Let’s see the code :

package com.javacodegeeks.java.core;

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

public class TimerTaskExample extends TimerTask {

	@Override
	public void run() {
		System.out.println("Start time:" + new Date());
		doSomeWork();
		System.out.println("End time:" + new Date());
	}

	// simulate a time consuming task
	private void doSomeWork() {
		try {

			Thread.sleep(10000);

		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void main(String args[]) {

		TimerTask timerTask = new TimerTaskExample();
		// running timer task as daemon thread
		Timer timer = new Timer(true);
		timer.scheduleAtFixedRate(timerTask, 0, 10 * 1000);
		System.out.println("TimerTask begins! :" + new Date());
		// cancel after sometime
		try {
			Thread.sleep(20000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		timer.cancel();
		System.out.println("TimerTask cancelled! :" + new Date());
		try {
			Thread.sleep(30000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

Output:

TimerTask begins! :Fri Jan 25 21:36:43 EET 2013
Start time:Fri Jan 25 21:36:43 EET 2013
End time:Fri Jan 25 21:36:53 EET 2013
Start time:Fri Jan 25 21:36:53 EET 2013
TimerTask cancelled! :Fri Jan 25 21:37:03 EET 2013
End time:Fri Jan 25 21:37:03 EET 2013

Don’t forget take a careful look a the documentation of Timer and TimerTask to explore all the features of this mechanism.

This was a Java Timer and TimerTask Example.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.