Java Timer Example

In Java, we have java.util.Timer class for scheduling the tasks at the frequent intervals. The steps for creating the simple job using the java.util.Timer class is:

  • Create the task / job by extending the java.util.TimerTask. A task has to extend java.util.TimerTask and implement the run() method
  • Create the Timer instance to manage the tasks. You can think this is the main part where all the tasks are controled. A timer instance might have many tasks registered with it.
  • Register the simple task created to the timer and schedule the frequency of job execution.
  • After the above steps, jobs will start tun at the specified intervals. You can terminate the job using cancel() method in the timer object.

Lets look at the simple example to understand the implementation of Timer in your Java  applications. If you have any questions, please write it in the comments section.

also read:

TimerSampleJob

package javabeat.net.java.core;

import java.util.TimerTask;

/**
 * Implementing Timer Job
 *
 * @author Krishna
 *
 */
public class TimerSampleJob extends TimerTask{
	private String jobName = null;
	private int i = 0;
	public TimerSampleJob(String jobName){
		System.out.println(jobName +" Registered!!");
		this.jobName = jobName;
	}

	@Override
	public void run() {
		i++;
		System.out.println(this.jobName + " Executed for " + i + " times!!" );
	}

}

TimerApplication.java

package javabeat.net.java.core;

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

/**
 * Time Job Sample Application
 *
 * @author Krishna
 *
 */
public class TimerApplication {

	public static void main(String[] args) {

		//Create timer instance
		Timer timer = new Timer();

		//Create Sample task for execution
		TimerTask task = new TimerSampleJob("Timer Sample Job 1");

		//Scheduling the task at specific intervals
		timer.scheduleAtFixedRate(task, 1000, 10000);

		//Making this main thread to sleep
		try{
			Thread.sleep(50000);
		}catch (InterruptedException exception){
			exception.printStackTrace();
		}
		System.out.println("Terminating the timer!!");
		//Terminating the timer.
		timer.cancel();
	}

}

Output…

Timer Sample Job 1 Registered!!
Timer Sample Job 1 Executed for 1 times!!
Timer Sample Job 1 Executed for 2 times!!
Timer Sample Job 1 Executed for 3 times!!
Timer Sample Job 1 Executed for 4 times!!
Timer Sample Job 1 Executed for 5 times!!
Terminating the timer!!

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*