Main Tutorials

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 Author

author image
Open Source Developer, TenthPlanet Technologies.

Comments

Subscribe
Notify of
17 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
vinod
8 years ago

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

EnGoPy
3 years ago
Reply to  vinod

You can use ScheduledExecutorService with .scheduleAtFixedRate. Than it try to run your method with set delay/period, but inside method you can check if current time is after 10 o’clock and before 12 o’clock.
It works pretty well.

Rahul Bavannavar
4 years ago
Reply to  vinod

Use Thread Scheduler and logger

Pranav
1 year ago

Brother this really helped me. Thank you!

Abhinandan
4 years ago

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
6 years ago

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
6 years ago
Reply to  Nicola M

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

Akshayraj Kore
8 years ago

How do I stop the run ?

saud siddiqui
4 years ago
Reply to  Akshayraj Kore

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

ramu
10 years ago

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
11 years ago

create a endless thread can work well.

Pankaj
11 years ago
Reply to  ymiao

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
11 years ago
Mohamed Sanaulla
11 years ago
Reply to  bluez

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.

Charlie
10 years ago

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

Ramesh Naidu
6 years ago
Reply to  Charlie

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

Dhina Prakash
10 years ago
Reply to  Charlie

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