Implementing Scheduled Tasks in Standard Java
Java provides built-in mechanisms for scheduling recurring tasks without relying on external frameworks. The two primary approaches are utilizing the java.util.Timer class or the more robust java.util.concurrent.ScheduledExecutorService.
Using Timer and TimerTask
The Timer class allows scheduling tasks for future execution in a background thread. A task must extend the TimerTask abstract class and override its run method.
import java.util.Timer;
import java.util.TimerTask;
import java.time.LocalDateTime;
public class DataCleanupJob extends TimerTask {
@Override
public void run() {
System.out.println("Executing data cleanup at: " + LocalDateTime.now());
}
public static void main(String[] args) {
Timer taskScheduler = new Timer();
// Schedule task to run immediately and repeat every 5 seconds
taskScheduler.schedule(new DataCleanupJob(), 0, 5000);
}
}
In this implementation, DataCleanupJob defines the logic to be executed. The Timer object invokes the schedule method, accepting the task instance, an initial delay (0 milliseconds in this case), and the period between subsequent executions (5000 milliseconds).
Using ScheduledExecutorService
For applications requiring greater flexibility and thread safety, ScheduledExecutorService is the preferred choice. It handles task scheduling using a thread pool, mitigating issues found in the legacy Timer API.
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.time.LocalDateTime;
public class HeartbeatMonitor implements Runnable {
@Override
public void run() {
System.out.println("Heartbeat signal sent at: " + LocalDateTime.now());
}
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
// Schedule task to run immediately and repeat every 5 seconds
scheduler.scheduleAtFixedRate(new HeartbeatMonitor(), 0, 5, TimeUnit.SECONDS);
}
}
Here, the HeartbeatMonitor class implements the Runnable interface. A single-threaded scheduled executor is instantiated, and the scheduleAtFixedRate method configures the task. This method requires the task, the initial delay, the period, and the TimeUnit for the delay and period parameters.