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,
- You should create a class extending TimerTask(available in
java.util
package). TimerTask is a abstract class. - Write your code in public void
run()
method that you want to execute periodically. - 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.
- Instantiate Timer Object
Timer time = new Timer();
- Instantiate Scheduled Task class Object
ScheduledTask st = new ScheduledTask();
- 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.
If your code does not contain termination, it will not stop. So you should use a program terminator.
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..
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.
Use Thread Scheduler and logger
Brother this really helped me. Thank you!
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 🙂
Hi, I should pass an argument with first timertask argument in time.schedule
(time.schedule(st(“string”),0,0).
How can I do It?
instead of ‘st’ , you can pass new ScheduledTask(arg1, arg2), where as in ScheduledTask class you better write a constructor
How do I stop the run ?
you have to use cancel() to cancel the timer…
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 ????
create a endless thread can work well.
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
Hi mkyong,
how about using scheduler..
like in this link..
http://stackoverflow.com/questions/7499534/applicationscope-bean-that-uses-a-timertask-sheduler-good-or-bad
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.
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…..
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
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