Sub topic 11
Delayed and Repeating Tasks with ScheduledExecutorService
Some work should not happen right away. You might want to retry a failed download in five seconds, or print a status report every minute. You could write a loop with Thread.sleep, but that ties up a thread and is easy to get wrong. Java gives you a better tool for this job: the ScheduledExecutorService.
This chapter shows how to run a task once after a delay, how to repeat a task on a schedule, and how to stop scheduled tasks safely.
What Is a ScheduledExecutorService?
A ScheduledExecutorService is an ExecutorService that can also run tasks later or run them again and again. It keeps everything you already know from earlier chapters: submit, Future, shutdown, and awaitTermination all still work. It adds scheduling methods on top.
You get one from the Executors factory:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
public class MakeScheduler {
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
System.out.println("Scheduler ready");
scheduler.shutdown();
}
}The number 1 is the pool size. A pool size is how many threads the scheduler keeps ready to run tasks. One thread is enough for light, quick tasks. If you have several tasks that may run at the same moment, use a bigger pool.
Each scheduling method returns a ScheduledFuture. A ScheduledFuture is a Future that also knows how long remains until the task runs. You use it to get a result or to cancel the task.
The Three Scheduling Methods
| Method | What it does | Runs how many times |
|---|---|---|
| `schedule(task, delay, unit)` | Waits `delay`, then runs the task | Once |
| `scheduleAtFixedRate(task, initialDelay, period, unit)` | Starts a run every `period`, measured from start to start | Until cancelled |
| `scheduleWithFixedDelay(task, initialDelay, delay, unit)` | Waits `delay` after each run finishes, then starts the next | Until cancelled |
The unit is a TimeUnit, such as TimeUnit.SECONDS or TimeUnit.MILLISECONDS. It tells Java how to read the numbers you pass.
Running a Task Once After a Delay
The schedule method runs a task one time, after a wait. It accepts either a Runnable (no result) or a Callable (returns a result). Here the task returns a String, so Java treats it as a Callable.
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class DelayDemo {
public static void main(String[] args) throws Exception {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
try {
ScheduledFuture<String> later = scheduler.schedule(
() -> "Hello after 2 seconds", 2, TimeUnit.SECONDS);
System.out.println("Waiting... about "
+ later.getDelay(TimeUnit.MILLISECONDS) + " ms left");
System.out.println(later.get());
} finally {
scheduler.shutdown();
}
}
}Here is what happens step by step:
schedulereturns at once. The main thread does not wait.getDelayreports how much time remains before the task runs.later.get()blocks until the task has run, then returns its result.- The
finallyblock shuts the scheduler down so the program can exit.
Repeating a Task at a Fixed Rate
scheduleAtFixedRate starts the task again and again at a steady beat. The beat is measured from the start of one run to the start of the next. This suits jobs like "sample the temperature every second."
The next program prints tick once per second, starting right away. A second, one-time task stops everything after 3.5 seconds.
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class ScheduleDemo {
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> tick = scheduler.scheduleAtFixedRate(
() -> System.out.println("tick"), 0, 1, TimeUnit.SECONDS);
scheduler.schedule(() -> {
tick.cancel(false);
scheduler.shutdown();
}, 3500, TimeUnit.MILLISECONDS);
}
}The output is four lines of tick, at 0, 1, 2, and 3 seconds. At 3.5 seconds the second task runs. It calls tick.cancel(false) to stop the repeating task. The false means "do not interrupt a run that is already going." Then it shuts the scheduler down.
A repeating task never ends on its own. It keeps going until you cancel it, shut down the scheduler, or the task throws an exception. You will see the exception case later in this chapter.
Repeating a Task with a Fixed Delay
scheduleWithFixedDelay measures the gap differently. It waits for a run to finish, then waits the delay, then starts the next run. This suits jobs like "check for new mail, then rest 30 seconds," where you always want a rest between runs.
This program shows the difference. Each run takes about half a second, and the delay is one second.
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class FixedDelayDemo {
public static void main(String[] args) throws InterruptedException {
long begin = System.currentTimeMillis();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleWithFixedDelay(() -> {
long elapsed = System.currentTimeMillis() - begin;
System.out.println("run starts at " + elapsed + " ms");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, 0, 1, TimeUnit.SECONDS);
Thread.sleep(5000);
scheduler.shutdown();
}
}The runs start about 1500 ms apart: 500 ms of work plus 1000 ms of delay. If you change scheduleWithFixedDelay to scheduleAtFixedRate, the runs start about 1000 ms apart, because the work time is now counted inside the period.
The main thread sleeps for five seconds before it shuts the scheduler down. Without that sleep, shutdown would happen right away and cancel the repeating task before it ran more than once.
What If a Run Takes Longer Than the Period?
Suppose a fixed-rate task has a period of one second, but one run takes three seconds. Java never starts a second copy of the same task while the first is still running. The next run starts as soon as the slow one ends. So runs of the same task never overlap. With a fixed rate the runs can bunch up after a slow one. With a fixed delay they never do.
A Hidden Trap: Exceptions Stop Repeating Tasks
This is the most common surprise with scheduled tasks. If a repeating task throws an exception, the scheduler stops running it. It prints nothing. No stack trace appears. The task just goes quiet.
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class SilentFailureDemo {
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
AtomicInteger count = new AtomicInteger();
scheduler.scheduleAtFixedRate(() -> {
int n = count.incrementAndGet();
System.out.println("run " + n);
if (n == 3) {
throw new IllegalStateException("boom");
}
}, 0, 500, TimeUnit.MILLISECONDS);
Thread.sleep(3000);
scheduler.shutdown();
}
}The program prints run 1, run 2, run 3, and then nothing more, even though it waits three seconds. The exception was saved inside the ScheduledFuture, and nobody looked at it.
The fix is to catch exceptions inside the task yourself:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class SafeRepeatDemo {
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
AtomicInteger count = new AtomicInteger();
scheduler.scheduleAtFixedRate(() -> {
try {
int n = count.incrementAndGet();
System.out.println("run " + n);
if (n == 3) {
throw new IllegalStateException("boom");
}
} catch (RuntimeException e) {
System.out.println("Run failed, will try again: " + e.getMessage());
}
}, 0, 500, TimeUnit.MILLISECONDS);
Thread.sleep(3000);
scheduler.shutdown();
}
}Now run 3 reports its failure, and runs 4, 5, and 6 still happen.
Shutting Down a Scheduler
You stop a scheduler the same way you stop any ExecutorService: call shutdown, wait with awaitTermination, and call shutdownNow if needed. Scheduled tasks add two details.
- After
shutdown, repeating tasks are cancelled. They do not run again. - After
shutdown, one-time delayed tasks that are already waiting still run when their time comes. The scheduler finishes them, then stops.
So if you schedule a task for ten minutes from now and then call shutdown, your program keeps running for ten more minutes. If you do not want that, cancel the task first or call shutdownNow, which drops all waiting tasks.
Why Not Use Thread.sleep in a Loop?
You could write while (true) { work(); Thread.sleep(1000); } in your own thread. That does work, but it has real costs:
- Every repeating job needs its own thread.
- You have to write your own code to stop the loop.
- Timing drifts, because the loop does not account for how long
work()took.
A scheduler shares a small pool of threads across many jobs, and it gives you cancel and shutdown for free. Older code sometimes uses java.util.Timer for this. Timer runs all its tasks on one thread, and one exception kills that thread and all its tasks. Prefer ScheduledExecutorService in new code.
Exercise
A task takes 2 seconds to run. You schedule it with scheduleWithFixedDelay, an initial delay of 0, and a delay of 3 seconds. About how far apart do the start times of runs 1 and 2 fall? What if you use scheduleAtFixedRate with a period of 3 seconds instead?
Show answer
With scheduleWithFixedDelay, the starts fall about 5 seconds apart: 2 seconds of work plus 3 seconds of delay. With scheduleAtFixedRate, they fall about 3 seconds apart, because the period is measured from start to start and the 2-second run fits inside it.
Exercise
A repeating task that saves a log file every minute worked for an hour and then stopped. No error appeared anywhere. What is the most likely cause, and how do you fix it?
Show answer
The task most likely threw an uncaught exception, for example a disk or file error. A repeating task that throws is cancelled without any message, and the exception sits unread in its ScheduledFuture. Fix it by wrapping the task body in try/catch so that you log the error and the next run still happens.
Exercise
Write a program that prints "Starting soon" right away, prints "Go!" after 2 seconds using schedule, and then exits cleanly.
Show answer
Create a scheduler with Executors.newScheduledThreadPool(1). Print "Starting soon". Call scheduler.schedule(() -> System.out.println("Go!"), 2, TimeUnit.SECONDS), then call scheduler.shutdown(). The program still exits cleanly, because a one-time delayed task that is already waiting still runs after shutdown. The scheduler then stops on its own.