Implementing Periodic Task Execution in Java Every Five Seconds

ScheduledExecutorService for Recurring Tasks

The ScheduledExecutorService interface is the standard way to run tasks at fixed intervals in modern Java. Unlike traditional timers, it utilizes a thread pool and provides robust control over task execution and life cycle management.

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TaskRunner {
    public static void main(String[] args) {
        // Initialize a single-threaded executor
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

        Runnable heartbeatTask = () -> {
            System.out.println("Task performed at timestamp: " + System.currentTimeMillis() / 1000);
        };

        // Schedule task: (Runnable, initialDelay, period, unit)
        executor.scheduleAtFixedRate(heartbeatTask, 0, 5, TimeUnit.SECONDS);
    }
}

Utilizing java.util.Timer

For simple or legacy applications, the java.util.Timer class offers a straightforward approach to scheduling background tasks. It is useful for basic scennarios where complex thread management is not required.

import java.util.Timer;
import java.util.TimerTask;

public class SimpleScheduler {
    public static void main(String[] args) {
        Timer jobTimer = new Timer();

        TimerTask recurringJob = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Execution triggered every 5000ms");
            }
        };

        // Parameters: task, delay (ms), period (ms)
        long startDelay = 0L;
        long interval = 5000L;
        
        jobTimer.scheduleAtFixedRate(recurringJob, startDelay, interval);
    }
}

Comparison Table

Feature ScheduledExecutorService Timer
Threading Uses a thread pool Single background thread
Error Handling One task failure doesn't stop others One exception kills the timer thread
Precision High (using nanoseconds) Moderate (using milliseconds)
Flexibility Supports multiple tasks Limited to single-threaded sequential execution

Tags: java Concurrency scheduling Timer ScheduledExecutorService

Posted on Fri, 06 Nov 2026 16:47:02 +0000 by joespenceley