Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Scheduled Tasks in Standard Java

Tech 1

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.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.