How to run a task periodically in Java

Some java application need to execute a method between a regular interval of time. For example GUI application should update some information from database.

1. Scheduler Task

For this functionality,

  1. You should create a class extending TimerTask(available in java.util package). TimerTask is a abstract class.
  2. Write your code in public void run() method that you want to execute periodically.
  3. Insert below code in your Main class.

import java.util.TimerTask;
import java.util.Date;
/**
 * 
 * @author Dhinakaran P.
 */
// Create a class extends with TimerTask
public class ScheduledTask extends TimerTask {

	Date now; // to display current time

	// Add your task here
	public void run() {
		now = new Date(); // initialize date
		System.out.println("Time is :" + now); // Display current time
	}
}

2. Run Scheduler Task

A class to run above scheduler task.

  1. Instantiate Timer Object Timer time = new Timer();
  2. Instantiate Scheduled Task class Object ScheduledTask st = new ScheduledTask();
  3. Assign scheduled task through Timer.shedule() method.

import java.util.Timer;

/**
 * 
 * @author Dhinakaran P.
 */

//Main class
public class SchedulerMain {
	public static void main(String args[]) throws InterruptedException {

		Timer time = new Timer(); // Instantiate Timer Object
		ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
		time.schedule(st, 0, 1000); // Create Repetitively task for every 1 secs

		//for demo only.
		for (int i = 0; i <= 5; i++) {
			System.out.println("Execution in Main Thread...." + i);
			Thread.sleep(2000);
			if (i == 5) {
				System.out.println("Application Terminates");
				System.exit(0);
			}
		}
	}
}

Output:


Execution in Main Thread....0
Time is :Tue Jun 19 14:21:42 IST 2012
Time is :Tue Jun 19 14:21:43 IST 2012
Execution in Main Thread....1
Time is :Tue Jun 19 14:21:44 IST 2012
Time is :Tue Jun 19 14:21:45 IST 2012
Execution in Main Thread....2
Time is :Tue Jun 19 14:21:46 IST 2012
Time is :Tue Jun 19 14:21:47 IST 2012
Execution in Main Thread....3
Time is :Tue Jun 19 14:21:48 IST 2012
Time is :Tue Jun 19 14:21:49 IST 2012
Execution in Main Thread....4
Time is :Tue Jun 19 14:21:50 IST 2012
Time is :Tue Jun 19 14:21:51 IST 2012
Application Terminates
Time is :Tue Jun 19 14:21:52 IST 2012
Note
If your code does not contain termination, it will not stop. So you should use a program terminator.

References

  1. java.util.Timer JavaDoc
  2. java.util.TimerTask JavaDoc

About the Author

author image
Dhina Prakash
Open Source Developer, TenthPlanet Technologies.

Comments

avatar
8 Comment threads
7 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
15 Comment authors
Rahul BavannavarAbhinandansaud siddiquiRamesh NaiduRohit Basu Recent comment authors
newest oldest most voted
vinod
Guest
vinod

Hi, I have got some requirement like i want to run a java program to do some task between two time intervals like 10’o clock to 12’o clock everyday… so please help how to accomplish my requirement… any help is really appreciated..

Rahul Bavannavar
Guest
Rahul Bavannavar

Use Thread Scheduler and logger

Charlie
Guest
Charlie

I have a doubt about this code.

Why the output prints twice???? It´s normal??. How Can I execute the timer to get only one print???

Thanks…..

Dhina Prakash
Guest
Dhina Prakash

Charlie,

Create Repetitively task for every 1 secs (time.schedule(st, 0, 1000)), In Main method for loop wait for two secs for every iteration. So two tasks run in between 2 secs.

Is it clear now.

Thanks

Ramesh Naidu
Guest
Ramesh Naidu

Hi Charlie, the method calls every one second but in the above loop while iterating we are sleeping the thread for 2 seconds, that is why it prints twice in a loop. if you want to print output once, then remove this ‘Thread.sleep(2000);’ and execute it no matter of iterations, it will calls every second

Abhinandan
Guest
Abhinandan

Hey, I need some help like I want to run a java program to do a task at 8:30 AM & 8:30 PM….The task is that it should delete all the files inside a Folder but it should not delete the folder…so please help me to write this code… thank you :)

Nicola M
Guest
Nicola M

Hi, I should pass an argument with first timertask argument in time.schedule
(time.schedule(st(“string”),0,0).
How can I do It?

Rohit Basu
Guest
Rohit Basu

instead of ‘st’ , you can pass new ScheduledTask(arg1, arg2), where as in ScheduledTask class you better write a constructor

Akshayraj Kore
Guest
Akshayraj Kore

How do I stop the run ?

saud siddiqui
Guest
saud siddiqui

you have to use cancel() to cancel the timer…

ramu
Guest
ramu

sir how do i increment a day by using Timer class ,ie,,. my applicatin want to trigger for every 24 hours .if i use the timer class method like timer.schedule(task,0,86400*100) and for testing i have executed the program and changed my system day ie,, i update it to 24 hours but the program which is in executin is not giving any output .can u give me any solution for it ????

ymiao
Guest
ymiao

create a endless thread can work well.

Pankaj
Guest
Pankaj

Timer and TimerTask execution doesn’t take into account the time it took to execute, read more at http://www.journaldev.com/1050/java-timer-and-timertask-example-tutorial

bluez
Guest
bluez
Mohamed Sanaulla
Guest
Mohamed Sanaulla

Its- ScheduledExecutorService: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html

This allows to schedule certain tasks periodically or after a certain delay.