CKTIS / Java
util.concurrent.ScheduledExecutorService: practical reference
util.concurrent.ScheduledExecutorService: practical reference: ScheduledExecutorService schedules one-shot tasks after relative delays and recurring tasks periodically.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
java.util.concurrent.ScheduledExecutorServiceScheduledExecutorService schedules one-shot tasks after relative delays and recurring tasks periodically.
Use scheduleAtFixedRate for schedule-based cadence and scheduleWithFixedDelay for a pause measured after the previous run ends.
An exception from a periodic execution suppresses later executions, and delay expiration does not guarantee an exact wall-clock instant.
A zero or negative delay requests immediate execution, a period must be positive, and successive executions of one periodic task never overlap.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
java.util.concurrent.ScheduledExecutorService executor = java.util.concurrent.Executors.newSingleThreadScheduledExecutor();
try { System.out.println(executor.schedule(() -> 42, 0, java.util.concurrent.TimeUnit.SECONDS).get()); } finally { executor.shutdown(); }
}
}
Result
42
The example exercises the documented element in a small deterministic program and compares exact standard output.