ScheduledExecutorService for Recurring Tasks
Schedule tasks at fixed rates or with fixed delays for polling and background maintenance work.
Why ScheduledExecutorService?
ScheduledExecutorService extends ExecutorService to support task scheduling. It replaces the legacy Timer/TimerTask classes with a thread-pool-backed, exception-safe scheduler.
import java.util.concurrent.*;
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
// One-shot delay
scheduler.schedule(
() -> System.out.println("Runs once after 3 seconds"),
3, TimeUnit.SECONDS
);
// Don't forget to shut down eventually:
// scheduler.shutdown();schedule: One-Shot Delay
schedule(task, delay, unit) runs the task once after the specified delay. Works with both Runnable and Callable:
ScheduledExecutorService s = Executors.newScheduledThreadPool(1);
// Runnable:
ScheduledFuture<?> sf1 = s.schedule(
() -> System.out.println("Runnable fired!"), 2, TimeUnit.SECONDS);
// Callable:
ScheduledFuture<Integer> sf2 = s.schedule(
() -> { System.out.println("Callable fired!"); return 42; },
2, TimeUnit.SECONDS);
System.out.println(sf2.get()); // 42 (after 2 seconds)All lessons in this course
- ExecutorService and Thread Pool Types
- Submitting Tasks: Runnable vs Callable
- Future and Error Handling
- ScheduledExecutorService for Recurring Tasks