Many times we have to write some set of task which can be executed after a certain interval of time. These types of task are called timer task.
So we can achieve it by using threads which will sleep for a certain amount of time and execute again. But wait, Can Java do this for me So that I can focus on logic instead of worrying about how to schedule tasks for me?
Yes, Java can do the scheduling thing for you. So you write your logic and let Java handle the scheduling work.
Java has 2 classes that will do this work for you.
- java.util.Timer
- java.util.TimerTask
java.util.Timer:
Timer in Java is a utility class which is used to schedule tasks. We can schedule one time and repeated execution of tasks. The timer is like an alarm that we use to set to wake up in the morning.
java.util.TimerTask:
TimerTask is an abstract class that implements the Runnable interface. To create our own TimerTask we need to extend this class and have to give an implementation of the run method.
After that, we can use the Timer class to schedule our task.
While scheduling tasks using Timer, always make sure that time interval is more than normal thread execution, otherwise, your task queue will keep growing. Because TimerTask will add new tasks to a task queue and wait for the previous task to be completed.
In the example, I will schedule my task at every 5 Sec but my task will take 10 Sec to complete so from the output you can clearly see one task is executed only if the previous is completed
Let’s see an example:
MyTask:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.genericclass; import java.util.Date; import java.util.TimerTask; import java.util.stream.IntStream; public class MyTask extends TimerTask { @Override public void run() { System.out.println("\n\nTask started at:"+new Date()); doTask(); System.out.println("Task Compleated at:"+new Date()); } private void doTask() { System.out.print("executing Task"); IntStream.range(0,10).forEach(n -> { System.out.print("."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }); System.out.println("\n Task done\n\n"); } } |
Driver:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.genericclass; import java.util.Timer; import java.util.TimerTask; public class Driver { public static void main(String[] args) { //TimerTask Object of MyTask class TimerTask task = new MyTask(); // Creates a new timer whose associated thread may be specified to run as a daemon Timer timer = new Timer(true); //Schedules the specified task for repeated fixed-rate execution, //beginning after the 0 millisecond delay and perform task after every 5sec. timer.scheduleAtFixedRate(task, 0, 5*1000); try { Thread.sleep(1*60*1000); //wait for one min to let the timer run } catch (InterruptedException e) { e.printStackTrace(); } timer.cancel(); //cancel the timer } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
Task started at:Mon May 07 03:09:55 IST 2018 executing Task.......... Task done Task Compleated at:Mon May 07 03:10:05 IST 2018 Task started at:Mon May 07 03:10:05 IST 2018 executing Task.......... Task done Task Compleated at:Mon May 07 03:10:15 IST 2018 Task started at:Mon May 07 03:10:15 IST 2018 executing Task.......... Task done Task Compleated at:Mon May 07 03:10:25 IST 2018 Task started at:Mon May 07 03:10:25 IST 2018 executing Task.......... Task done Task Compleated at:Mon May 07 03:10:35 IST 2018 Task started at:Mon May 07 03:10:35 IST 2018 executing Task.......... Task done Task Compleated at:Mon May 07 03:10:45 IST 2018 Task started at:Mon May 07 03:10:45 IST 2018 executing Task.......... |
The timer will wait for it to finish and once finished, it will start again the next task from the queue.
Timer cancels () method is used to terminate the timer and discard any scheduled tasks, however, it doesn’t interfere with the currently executing task and let it finish. If the timer runs as a daemon thread, it will terminate as soon as all the main thread is finished executing.
That’s all on quick demo on Scheduling Tasks in Java.