Scheduled Executor Service Tasks

Uses ScheduledExecutorService to run delayed and periodic tasks, demonstrating fixed-rate and fixed-delay scheduling with proper shutdown handling.

JavaResilience

Code

snippet
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

public class ScheduledExecutorTasks {

    public static void main(String[] args) throws Exception {
        AtomicInteger counter = new AtomicInteger(0);

        try (ScheduledExecutorService scheduler =
                 Executors.newScheduledThreadPool(2)) {

            ScheduledFuture<?> fixedRate = scheduler.scheduleAtFixedRate(() -> {
                int count = counter.incrementAndGet();
                System.out.println("Fixed-rate task #" + count +
                    " at " + System.currentTimeMillis() % 10000);
            }, 0, 500, TimeUnit.MILLISECONDS);

            ScheduledFuture<?> fixedDelay = scheduler.scheduleWithFixedDelay(() -> {
                System.out.println("Fixed-delay task at " +
                    System.currentTimeMillis() % 10000);
            }, 100, 1000, TimeUnit.MILLISECONDS);

            scheduler.schedule(() -> {
                System.out.println("One-shot delayed task");
                return null;
            }, 2, TimeUnit.SECONDS);

            Thread.sleep(3000);
            fixedRate.cancel(false);
            fixedDelay.cancel(false);
        }

        System.out.println("Total executions: " + counter.get());
        System.out.println("Scheduler shutdown complete");
    }
}

Inside the snippet

Scheduled Executor Service Tasks is built around the class ScheduledExecutorTasks.

Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

Putting it to use

Each run prints the 5 labeled blocks Fixed-rate task #, Fixed-delay task at, One-shot delayed task, Total executions:, Scheduler shutdown complete in source order.

Core lines

Thread.sleep(3000);

Interactive Tools for This Topic

FAQ

What does Scheduled Executor Service Tasks print when run?
Execute the whole file; each printed line is prefixed with a label like `Fixed-rate task #`, `Fixed-delay task at`, `One-shot delayed task`.