JAVA: Schedule Task in Java

Timer Task

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.

  1.  java.util.Timer
  2. 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 tasksThe 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:

Driver:

Output:

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.