Sub topic 11
Delayed and Repeating Tasks with ScheduledExecutorService
Sometimes a task should not run right away. You may want it to run in five seconds. You may want it to run every minute, like a clock. Java has a special kind of executor for this job.
What It Is
A ScheduledExecutorService is an ExecutorService that can run tasks later or run them again and again. A delay is the amount of time to wait before a task starts. A period is the time between repeated runs.
You create one with a factory method:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);The number 1 is how many threads the pool keeps. One thread is enough for small, quick tasks.
Why It Matters
Without a scheduler, you might write a loop that calls Thread.sleep and then does some work. That ties up a thread and is easy to get wrong. A scheduler handles the timing for you. It also lets you cancel a repeating task cleanly.
Common uses include:
- Checking a server's health every 30 seconds
- Saving a backup every hour
- Timing out a request that takes too long
The Three Scheduling Methods
| Method | What it does |
|---|---|
| `schedule(task, delay, unit)` | Runs the task once, after the delay |
| `scheduleAtFixedRate(task, initialDelay, period, unit)` | Runs the task repeatedly. Each start time is measured from the previous start time |
| `scheduleWithFixedDelay(task, initialDelay, delay, unit)` | Runs the task repeatedly. Each wait begins when the previous run finishes |
A TimeUnit is an enum that names the unit of time, such as TimeUnit.SECONDS or TimeUnit.MILLISECONDS.
Each method returns a ScheduledFuture. This is a Future that also knows how long until the task runs. You can call cancel on it to stop the task.
A Worked Example
This program prints "tick" once per second, starting right away. After 3.5 seconds, a one-time task cancels the ticking and shuts down the scheduler.
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:
tick
tick
tick
tickHere is what each part does:
scheduleAtFixedRatestarts the ticking with an initial delay of0and a period of1second.schedulesets up a single task to run at 3500 milliseconds.- That task calls
tick.cancel(false). Thefalsemeans "do not interrupt the task if it is running right now." - It then calls
scheduler.shutdown(). Without this call, the scheduler's thread keeps the program alive forever.
Fixed Rate or Fixed Delay?
Suppose a task takes 0.4 seconds to run and the period is 1 second.
- With fixed rate, runs start at 0, 1, 2, 3 seconds. The schedule follows the clock.
- With fixed delay, runs start at 0, 1.4, 2.8, 4.2 seconds. Each wait starts after the last run ends.
Use fixed rate when timing matters, such as a clock. Use fixed delay when you need a rest between runs, such as polling a slow service.
Exercise
A repeating task takes 2 seconds to run. You schedule it with scheduleWithFixedDelay(task, 0, 3, TimeUnit.SECONDS). At what times do the first three runs start?
Show answer
At 0, 5, and 10 seconds. Each run takes 2 seconds, and the 3-second delay begins only after a run ends, so every start is 5 seconds after the previous one.
Exercise
In ScheduleDemo, what happens if you remove the line scheduler.shutdown()?
Show answer
The ticking still stops because of tick.cancel(false), but the scheduler's thread stays alive. The program never exits on its own.