ScheduledExecutorService for Recurring Tasks
Schedule tasks at fixed rates or with fixed delays for polling and background maintenance work.
ScheduledExecutorService for Recurring Tasks is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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)scheduleAtFixedRate
scheduleAtFixedRate(task, initialDelay, period, unit) runs the task repeatedly at a fixed rate. If a task takes longer than the period, the next execution starts immediately after it finishes (no overlap).
ScheduledExecutorService s = Executors.newScheduledThreadPool(1);
AtomicInteger count = new AtomicInteger();
ScheduledFuture<?> sf = s.scheduleAtFixedRate(
() -> System.out.println("Tick " + count.incrementAndGet()),
0, // initial delay
1, // period
TimeUnit.SECONDS
);
Thread.sleep(5000);
sf.cancel(false); // stop after 5 ticks
s.shutdown();scheduleWithFixedDelay
scheduleWithFixedDelay(task, initialDelay, delay, unit) waits the specified delay AFTER each task completes before starting the next. Good for polling where task duration varies.
s.scheduleWithFixedDelay(
() -> {
System.out.println("Polling... " + Instant.now());
// variable-length polling task
},
0, // no initial delay
5, // 5-second gap AFTER each completion
TimeUnit.SECONDS
);
// Next execution = task end + 5 seconds (not task start)Fixed Rate vs Fixed Delay
Key distinction:
- scheduleAtFixedRate: next start = last start + period (drift-free timing)
- scheduleWithFixedDelay: next start = last finish + delay (guaranteed gap between executions)
Use fixedRate for heartbeats; fixedDelay for polling where task duration varies.
ScheduledFuture: Cancellation
schedule/scheduleAtFixedRate/scheduleWithFixedDelay return a ScheduledFuture. Call cancel(false) to stop future executions without interrupting the running one:
ScheduledFuture<?> sf = scheduler.scheduleAtFixedRate(
() -> System.out.println("Heartbeat"), 0, 1, TimeUnit.SECONDS);
// Cancel after 5 seconds
scheduler.schedule(() -> sf.cancel(false), 5, TimeUnit.SECONDS);Exception Handling in Scheduled Tasks
If a scheduled task throws an uncaught exception, the scheduler silently stops recurring — no more executions. Always wrap in try-catch:
scheduler.scheduleAtFixedRate(() -> {
try {
// risky work
if (Math.random() < 0.3) throw new RuntimeException("transient");
System.out.println("Success");
} catch (Exception e) {
System.err.println("Task error: " + e.getMessage());
// task continues to run on next interval
}
}, 0, 2, TimeUnit.SECONDS);Practical: Cache Refresh
Use a scheduled task to refresh a cache periodically:
class PriceCache {
private volatile Map<String, Double> prices = new HashMap<>();
PriceCache(ScheduledExecutorService scheduler) {
scheduler.scheduleAtFixedRate(this::refresh, 0, 30, TimeUnit.SECONDS);
}
private void refresh() {
System.out.println("Refreshing prices...");
// prices = fetchFromDatabase();
}
Double getPrice(String symbol) { return prices.get(symbol); }
}Practical: Retry with Backoff
Implement exponential backoff retry using scheduled tasks:
void retryWithBackoff(Runnable task, int maxRetries, ScheduledExecutorService s) {
AtomicInteger attempts = new AtomicInteger(0);
long[] delay = {1}; // seconds
Runnable wrapper = new Runnable() {
public void run() {
try {
task.run();
} catch (Exception e) {
int n = attempts.incrementAndGet();
if (n < maxRetries) {
delay[0] *= 2;
s.schedule(this, delay[0], TimeUnit.SECONDS);
} else System.err.println("Max retries reached");
}
}
};
s.execute(wrapper);
}Monitoring: getDelay and getQueue
Inspect the scheduler's state:
ScheduledFuture<?> sf = scheduler.schedule(() -> {}, 10, TimeUnit.SECONDS);
System.out.println("Delay remaining: " + sf.getDelay(TimeUnit.SECONDS) + "s");
// ThreadPoolExecutor provides queue inspection:
if (scheduler instanceof ScheduledThreadPoolExecutor ste) {
System.out.println("Queue size: " + ste.getQueue().size());
}Shutdown and Drain
On shutdown, decide whether scheduled tasks should still run:
ScheduledThreadPoolExecutor ste = (ScheduledThreadPoolExecutor)
Executors.newScheduledThreadPool(2);
// Cancel scheduled tasks on shutdown (default: false = they run)
ste.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
ste.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
ste.shutdown();Quick Check
A task scheduled with scheduleAtFixedRate(..., 1, TimeUnit.SECONDS) takes 3 seconds to complete. How does the scheduler handle this?
Recap: ScheduledExecutorService
Key takeaways:
- schedule() — one-shot with delay
- scheduleAtFixedRate() — drift-free timing (start-to-start)
- scheduleWithFixedDelay() — guaranteed gap (finish-to-start)
- Uncaught exceptions silently stop recurring tasks — always wrap in try-catch
- Cancel with ScheduledFuture.cancel(false)
Frequently asked questions
Is the “ScheduledExecutorService for Recurring Tasks” lesson free?
Yes — the full text of “ScheduledExecutorService for Recurring Tasks” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “ScheduledExecutorService for Recurring Tasks”?
Schedule tasks at fixed rates or with fixed delays for polling and background maintenance work. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “ScheduledExecutorService for Recurring Tasks” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- ExecutorService and Thread Pool Types
- Submitting Tasks: Runnable vs Callable
- Future and Error Handling
- ScheduledExecutorService for Recurring Tasks