Run tasks later and repeatedly
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A fee reminder must go out in ten minutes, and a "server alive" signal every five seconds. Writing your own sleep loops for this is messy. What does Java offer for timed and repeating work?
ScheduledExecutorService.schedule
ScheduledExecutorService is a thread pool that can run a task once after a delay, or again and again on a fixed schedule.
schedule(task, delay, unit) runs a task once, after the given delay. The task can be a Runnable or a Callable. It returns a ScheduledFuture, a Future that also knows how long is left before the task runs (getDelay).
Example 1 · Three reminders run in order of their delay
import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;
public class RemindersDemo { public static void main(String[] args) throws Exception { ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.schedule(() -> System.out.println("Reminder: hostel fee due today"), 150, TimeUnit.MILLISECONDS); scheduler.schedule(() -> System.out.println("Reminder: lab record submission"), 50, TimeUnit.MILLISECONDS); scheduler.schedule(() -> System.out.println("Reminder: library book due"), 100, TimeUnit.MILLISECONDS); ScheduledFuture<String> otp = scheduler.schedule(() -> "OTP 4821", 200, TimeUnit.MILLISECONDS);
System.out.println("All scheduled; main carries on"); System.out.println("Got " + otp.get()); // waits about 200 ms scheduler.shutdown(); }}All scheduled; main carries on Reminder: lab record submission Reminder: library book due Reminder: hostel fee due today Got OTP 4821
What this code does
schedulereturns at once, so main prints first. The reminders then run in order of their delay (50, 100, 150 ms), not the order in which they were scheduled.- The last task is a
Callable, so itsScheduledFuture<String>carries a value;get()waits until it has run and returnsOTP 4821.
You create the pool with Executors.newScheduledThreadPool(n), or Executors.newSingleThreadScheduledExecutor() for one thread. The calling thread does not wait: schedule returns at once, and a pool thread runs the task when its time comes. With one thread, tasks run in order of their due time, not the order in which you scheduled them.
java.util.Timer. It has a single thread, and one task that throws kills that thread and every other task on the timer. A scheduled pool does not have that problem.scheduleAtFixedRate versus scheduleWithFixedDelay
Fixed rate and fixed delay are the two ways to repeat a task: fixed rate starts runs on a fixed clock, fixed delay waits a set time after each run ends.
Both run a task again and again until you cancel it. They differ in what the gap is measured from.
Example 2 · Fixed rate versus fixed delay, measured
import java.util.ArrayList;import java.util.List;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;
public class RateVersusDelayDemo { static List<Long> startTimes(ScheduledExecutorService pool, boolean fixedRate) throws InterruptedException { List<Long> starts = new ArrayList<>(); Runnable task = () -> { synchronized (starts) { starts.add(System.nanoTime()); } try { Thread.sleep(60); // each run takes 60 ms } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }; ScheduledFuture<?> f = fixedRate ? pool.scheduleAtFixedRate(task, 0, 100, TimeUnit.MILLISECONDS) : pool.scheduleWithFixedDelay(task, 0, 100, TimeUnit.MILLISECONDS); Thread.sleep(450); f.cancel(false); Thread.sleep(100); // let a running pass finish
List<Long> ms = new ArrayList<>(); synchronized (starts) { for (long t : starts) { ms.add((t - starts.get(0)) / 1_000_000); // ms after the first start } } return ms; }
public static void main(String[] args) throws InterruptedException { ScheduledExecutorService pool = Executors.newScheduledThreadPool(1); System.out.println("Fixed rate, starts at ms: " + startTimes(pool, true)); System.out.println("Fixed delay, starts at ms: " + startTimes(pool, false)); pool.shutdown(); }}Fixed rate, starts at ms: [0, 100, 211, 312, 403] Fixed delay, starts at ms: [0, 180, 351]
What this code does
- Fixed rate keeps the 100 ms clock: the 60 ms of work happens inside each gap. Fixed delay adds the 60 ms of work to the 100 ms pause, so runs start at least 160 ms apart and fewer runs fit in the same 450 ms.
- Times are measured from the first start. The exact numbers change from run to run by a few milliseconds (more on Windows), because the operating system decides exactly when a sleeping thread wakes up.
- Fixed rate: a clock tick that must stay regular, such as a heartbeat every 5 seconds or a per-minute report.
- Fixed delay: a pause between jobs, such as polling a slow result server and resting 30 seconds after each reply.
- Stop either one with
future.cancel(false), or by shutting the pool down.
scheduleAtFixedRate(task, initialDelay, period, unit) plans start times on a fixed clock: at initialDelay, then every period after that. How long each run takes does not move the plan. scheduleWithFixedDelay(task, initialDelay, delay, unit) waits delay after each run ends before starting the next one. Take a task that runs for 60 ms, with a period or delay of 100 ms. Fixed rate starts it at 0, 100, 200 and 300 ms; fixed delay starts it at 0, 160, 320 and 480 ms. If one fixed-rate run takes longer than the period, the next run starts late; runs of the same task never overlap.
An exception silently stops a repeating task
If one run of a repeating task throws an exception, every later run is cancelled. Nothing is printed: as with submit, the exception is stored in the task's ScheduledFuture. The heartbeat just stops, and nobody knows why.
Example 3 · A heartbeat that dies without a word
import java.util.concurrent.ExecutionException;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;
public class SilentStopDemo { public static void main(String[] args) throws InterruptedException { ScheduledExecutorService pool = Executors.newScheduledThreadPool(1); AtomicInteger beats = new AtomicInteger();
ScheduledFuture<?> heartbeat = pool.scheduleAtFixedRate(() -> { int n = beats.incrementAndGet(); System.out.println("beat " + n); if (n == 3) { String server = null; // a bug on the 3rd beat server.length(); } }, 0, 30, TimeUnit.MILLISECONDS);
Thread.sleep(300); // time for about 10 beats System.out.println("Beats after 300 ms: " + beats.get()); System.out.println("Heartbeat done? " + heartbeat.isDone()); try { heartbeat.get(); } catch (ExecutionException e) { System.out.println("Hidden cause: " + e.getCause().getClass().getSimpleName()); } pool.shutdown(); }}beat 1 beat 2 beat 3 Beats after 300 ms: 3 Heartbeat done? true Hidden cause: NullPointerException
What this code does
- The third beat threw a
NullPointerException. No stack trace appeared, and all later beats were cancelled: after 300 ms there are still only 3 beats instead of about 10. isDone()becametrue, which a healthy repeating task never is. Onlyget()reveals the cause, wrapped inExecutionException.
Example 4 · The fix: catch inside the repeating task
import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;
public class SafeHeartbeatDemo { static final AtomicInteger beats = new AtomicInteger();
static void beat() { int n = beats.incrementAndGet(); if (n == 3) { throw new IllegalStateException("network glitch"); } System.out.println("beat " + n); }
public static void main(String[] args) throws InterruptedException { ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> heartbeat = pool.scheduleAtFixedRate(() -> { try { beat(); } catch (RuntimeException e) { // log it and keep the schedule alive System.out.println("beat failed: " + e.getMessage()); } }, 0, 50, TimeUnit.MILLISECONDS);
while (beats.get() < 5) { Thread.sleep(10); } heartbeat.cancel(false); pool.shutdown(); pool.awaitTermination(1, TimeUnit.SECONDS); System.out.println("Heartbeat cancelled after " + beats.get() + " beats"); }}beat 1 beat 2 beat failed: network glitch beat 4 beat 5 Heartbeat cancelled after 5 beats
What this code does
- The
try/catchinside the lambda turns a failed run into a log line. The exception never reaches the scheduler, so beats 4 and 5 still happen. - Main waits until 5 beats have happened, then cancels the task with
cancel(false)and shuts the pool down.beatsis anAtomicInteger, so main sees the latest count safely.
The stored exception comes out only if someone calls get() on that future, which then throws ExecutionException. For a repeating task that rarely happens, because get() on a healthy repeating task blocks until it is cancelled. The usual fix is to wrap the body of a repeating task in try/catch and log the error, so one bad run does not end the schedule.
isDone() turning true on its own is a sign the task has died.A reminder and heartbeat example
A heartbeat is a small message sent at a fixed rate to say "I am still alive". A reminder is a one-time message after a delay, such as "10 minutes left".
Example 5 · Exam hall heartbeat with a "time up" reminder
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;
public class ExamMonitorDemo { public static void main(String[] args) throws Exception { ScheduledExecutorService pool = Executors.newScheduledThreadPool(2); BlockingQueue<String> beats = new ArrayBlockingQueue<>(100); AtomicInteger n = new AtomicInteger();
ScheduledFuture<?> heartbeat = pool.scheduleAtFixedRate(() -> { try { beats.offer("Hall 3 alive, beat " + n.incrementAndGet()); } catch (RuntimeException e) { System.out.println("heartbeat error: " + e); } }, 0, 40, TimeUnit.MILLISECONDS);
for (int i = 0; i < 4; i++) { System.out.println(beats.take()); // waits for the next beat }
heartbeat.cancel(false); ScheduledFuture<String> timeUp = pool.schedule( () -> "Reminder: time up, hand in the answer sheets", 60, TimeUnit.MILLISECONDS); System.out.println("Heartbeat stopped: " + heartbeat.isCancelled()); System.out.println(timeUp.get());
pool.shutdown(); }}Hall 3 alive, beat 1 Hall 3 alive, beat 2 Hall 3 alive, beat 3 Hall 3 alive, beat 4 Heartbeat stopped: true Reminder: time up, hand in the answer sheets
What this code does
- The heartbeat puts a message into a
BlockingQueueevery 40 ms, and main prints them withtake(). That keeps all printing on one thread, so the output order is fixed. - After 4 beats main cancels the repeating task and schedules a one-time reminder with
schedule(Callable, ...);get()waits for it. The heartbeat body is wrapped intry/catch, the habit from the previous example.
An exam portal's server might send a heartbeat every few seconds so a monitor can raise an alarm when the beats stop.
Both fit one scheduled pool: scheduleAtFixedRate for the beats and schedule for the reminder. When you are done, cancel the repeating task and shut the pool down. By default shutdown() cancels repeating tasks, while one-time delayed tasks that are already scheduled still run.
Next step
Check your understanding
12 quick questions