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");
    }
}