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

17 comments on “How to run a task periodically in Java

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

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

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

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

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

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

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

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

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

Leave a Comment

Your email address will not be published. Required fields are marked *