Image by Timisu from pixabay.com
Introduction
The use of scheduled tasks is very common in large and medium-sized systems, mainly because they have several functionalities linked to the automation of tasks without human intervention. It is common to see the use of tools like crontab (Linux) for scheduling tasks, be they in Java or another language.
Task Schedulers: TimerTask
The Java language natively already has a task scheduler that can be exploited through the TimerTask class.
The TimerTask class is an abstract class that implements the Runnable interface, used when we need to work with multi-thread, as shown in Listing 1.
package java.util; public abstract class TimerTask implements Runnable { final Object lock = new Object(); int state = VIRGIN; static final int VIRGIN = 0; static final int SCHEDULED = 1; static final int EXECUTED = 2; static final int CANCELLED = 3; long nextExecutionTime; long period = 0; protected TimerTask() { } public abstract void run(); public boolean cancel() { synchronized(lock) { boolean result = (state == SCHEDULED); state = CANCELLED; return result; } } public long scheduledExecutionTime() { synchronized(lock) { return (period < 0 ? nextExecutionTime + period : nextExecutionTime - period); } } }
The method that interests us in the above listing is the “public abstract void run ()”, it will be responsible for executing our logic at preconfigured intervals. As you may have already noticed the principle for using the TimeTask class is to extend it and implement the run () method, since this is abstract and its implementation is mandatory. So that’s exactly what we’re going to do, as shown in Listing 2.
Listing 2. Extending the TimerTask class
import java.util.Date; import java.util.TimerTask; public class Scheduler extends TimerTask { Date instanteAtual; @Override public void run() { instanteAtual = new Date(); System.out.println(instanteAtual); } }
public class StartScheduler { public static void main(String[] args) { Timer timer = new Timer(); Scheculer scheduler = new Scheduler(); timer.schedule(scheduler, 0, 1000); while(true){ System.out.println("execution alert ..."); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
Timer timer = new Timer();
Scheduler scheduler = new Scheduler();
public void schedule(TimerTask task, long delay, long period)
timer.schedule(scheduler, 0, 1000);
That tells us that our task will be executed one at a time without delay to start, that is, as soon as this line is executed the task will be initialized immediately.
Conclusion
For many cases, TimerTask is an incredible tool that helps solve problems that would need a whole technological infrastructure to be solved, so we do not become “slaves” of tools external to Java, bringing everything needed into a single place, performing a true “inbox”, all in one place.