ScheduledExecutorService submits delayed or periodic work and returns futures that expose completion, failure and cancellation.
Java scheduled tasks: delay semantics and failed repetitions
Java 8+. This is a complete program using JDK classes.
Distinguish two recurring schedules
Fixed-rate scheduling uses planned start times. Fixed-delay scheduling waits for one execution to finish before counting the delay to the next. A slow task can therefore produce different behavior under the two policies even when the configured number is the same.
The one-shot program schedules one renewal operation, then waits for its result with a separate timeout. Scheduling a delay does not guarantee execution at an exact wall-clock instant. Busy workers, operating-system scheduling and the task itself affect actual completion.
An exception escaping a periodic task can suppress later executions. Store and inspect its future or define explicit failure reporting inside the task. Silently swallowing all failures turns a broken renewal into a process that appears healthy while its state stops changing.
Own the scheduler
The application that creates the scheduler closes it. shutdown stops new admission; awaitTermination checks whether admitted work has finished. Long-running services also need a decision about remaining delayed tasks and shutdown deadlines instead of leaving that policy to a process exit.
Working program
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class RenewalSchedule {
public static void main(String[] args) throws Exception {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
try {
ScheduledFuture<String> renewal = scheduler.schedule(() -> "renewed=R-31", 0, TimeUnit.MILLISECONDS);
System.out.println(renewal.get(2, TimeUnit.SECONDS));
} finally {
scheduler.shutdownNow();
if (!scheduler.awaitTermination(2, TimeUnit.SECONDS)) throw new IllegalStateException("Worker did not stop");
}
}
}Output
renewed=R-31Costs and boundaries
A scheduled task can remain queued until its delay elapses and a worker is available. The queue and retained task inputs contribute memory proportional to admitted pending work. A scheduling API does not provide durable storage or a distributed scheduler across server instances.
Common Mistakes
- Delay expiration is not a completion deadline.
- An uncaught periodic-task failure needs reporting.
- Do not create a new scheduler for every incoming request.
