Skip to content
Tutorials Center
My learning

Topics

Lesson 139 of 201 ยท Concurrency

Timer and ScheduledExecutorService

Schedule delayed and repeating tasks in Java with Timer and ScheduledExecutorService - fixed rate versus fixed delay, cancelling, error handling and clean shutdown.

Plenty of programs need to do something later or again and again: show a reminder after five minutes, refresh a cache every hour, send a heartbeat every ten seconds, time out a request that takes too long. Writing a while loop with Thread.sleep works for a toy, but it ties up a thread, drifts over time and is awkward to stop.

Java gives you two scheduling tools. The old one is java.util.Timer (Java 1.3). The modern one is ScheduledExecutorService (Java 5), part of the executor framework from Executors and Thread Pools. This lesson shows both so that you can read old code, explains why the second one is almost always the better choice, and clears up the most confusing question in scheduling: the difference between fixed rate and fixed delay.

Time-based examples are tricky to keep repeatable, so these programs use a CountDownLatch to wait for the exact number of runs and print only things that do not depend on exact timing.

Timer and TimerTask

A Timer owns one background thread and a queue of tasks. You describe a task by extending TimerTask and schedule it.

Java A one-shot and a repeating Timer task

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The main methods are schedule(task, delay), schedule(task, delay, period) and scheduleAtFixedRate(task, delay, period). TimerTask.cancel() cancels one task, Timer.cancel() ends the whole timer. If you forget the last call the timer thread keeps the JVM alive; a new Timer(true) creates a daemon timer that does not.

Why Timer is considered obsolete

Timer has three design problems that bite in real programs:

  1. One thread for everything. If one task runs for a long time, every other task waits and starts late.
  2. An uncaught exception kills the timer. The single thread dies, all remaining tasks are dropped, and the timer refuses new ones.
  3. It uses the system clock. It is tied to wall-clock time, so changing the clock can disturb schedules.

The second problem is the most dangerous because it looks fine in testing:

Java One bad task kills the whole Timer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The stack trace of the first exception goes to standard error (not shown in the output panel), and then the timer is dead. For anything beyond a quick script, use the scheduled executor.

ScheduledExecutorService

A scheduled executor is a thread pool with a delay queue. You create it with Executors.newScheduledThreadPool(n) (or newSingleThreadScheduledExecutor()) and use these methods:

Method What it does
schedule(task, delay, unit) run once after the delay (a Runnable, or a Callable that returns a value)
scheduleAtFixedRate(task, initialDelay, period, unit) run every period, measured from start to start
scheduleWithFixedDelay(task, initialDelay, delay, unit) run, wait delay after it ends, run again

Each call returns a ScheduledFuture, which you can use to cancel the task, check getDelay(unit), or (for Callable) get the result with get().

Java Delayed tasks and a result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Repeating work and stopping it

For repeating tasks, a CountDownLatch lets main wait for a number of runs, and cancel on the returned future ends the repetition.

Java A heartbeat that stops itself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice cancel(false) versus cancel(true): true also interrupts the thread if the task is running right now. When you cancel a repeating task, no further runs start in either case.

Fixed rate versus fixed delay

This is the question everybody asks, and the timeline makes it clear. Suppose the task takes 200 ms to run and the period is 100 ms (so the work is longer than the period, to make the difference obvious):

flowchart LR
    subgraph Rate["Fixed rate (period 100 ms)"]
        direction LR
        R1["run 1<br/>0 to 200 ms"] -->|"already late:<br/>start at once"| R2["run 2<br/>200 to 400 ms"] -->|"start at once"| R3["run 3<br/>400 to 600 ms"]
    end
    subgraph Delay["Fixed delay (delay 100 ms)"]
        direction LR
        D1["run 1<br/>0 to 200 ms"] -->|"wait 100 ms"| D2["run 2<br/>300 to 500 ms"] -->|"wait 100 ms"| D3["run 3<br/>600 to 800 ms"]
    end

Fixed rate tries to keep to the clock and starts late runs the moment the previous one ends; fixed delay always waits the full gap after each run.

  • scheduleAtFixedRate aims for starts at 0, 100, 200, 300 and so on. If a run is late, the next one starts immediately afterwards to catch up, but the runs of one task never overlap. Use it for things that should happen N times per minute: a metrics sampler, a clock tick.
  • scheduleWithFixedDelay waits delay after each run finishes. The gap between the end of one run and the start of the next is always the same. Use it for work where you want a rest between rounds: polling a queue, cleaning up files.
Java Measuring the gaps between runs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

With fixed rate the work is longer than the period, so each run starts right after the previous one ends (a gap of about 200 ms). With fixed delay the gap is the 200 ms of work plus the 100 ms pause, about 300 ms. If the task is always faster than its period, the two policies look almost identical at first, but fixed rate stays on its schedule while fixed delay slowly drifts later.

Errors in scheduled tasks: the silent stop

The scheduled executor does not die when a task throws, but it does something that surprises people just as much: if a repeating task throws, all its future runs are cancelled silently. The exception is stored in the ScheduledFuture and only appears if you call get(). Always catch exceptions inside the task you repeat:

Java The silent stop, and the try/catch fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Shutting down properly

A scheduled executor's threads are non-daemon by default, so forgetting to shut it down keeps your program running forever. The shutdown methods differ in what they do with queued work:

  • shutdown() stops accepting tasks. By default, repeating tasks are cancelled and delayed one-shot tasks still run (you can change this with setExecuteExistingDelayedTasksAfterShutdownPolicy(false)).
  • shutdownNow() also drops waiting tasks and interrupts running ones.
  • awaitTermination(timeout, unit) waits for the pool to finish after shutdown().

Choosing a scheduler

  • Use ScheduledExecutorService for new code: several threads, exceptions that don't kill the scheduler, a returned future, and a monotonic clock.
  • A repeating job that must not drift and must not overlap itself: scheduleAtFixedRate (it never overlaps with itself).
  • A job with a pause between rounds: scheduleWithFixedDelay.
  • Schedules like "every day at 02:00" or "the first Monday of the month" need cron-style scheduling, which the JDK doesn't have. Frameworks fill the gap: Spring's @Scheduled, Quartz, or your server's own cron. The standard pattern in plain Java is to compute the delay until the next run with java.time (Dates and Times) and use schedule again each time.
  • Timeouts on other work: CompletableFuture.orTimeout (CompletableFuture) uses a scheduler internally.

Tip: Inject the scheduler into your classes instead of creating one inside. Tests can then pass a fake and avoid waiting for real time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A TimerTask throws an unchecked exception. What happens to the Timer?

    A Timer has one thread. An uncaught exception ends it, and later schedule calls throw IllegalStateException.
  2. 2. A task takes 300 ms and is scheduled with scheduleWithFixedDelay(task, 0, 100, MILLISECONDS). What is the time between the starts of two consecutive runs?

    Fixed delay waits 100 ms after each run ends, so the gap between starts is the 300 ms of work plus 100 ms.
  3. 3. A repeating task submitted with scheduleAtFixedRate throws an exception on its third run. What do you observe?

    The exception cancels future runs and is stored in the ScheduledFuture. Catch exceptions inside repeating tasks.
  4. 4. Which statement about scheduleAtFixedRate is true?

    A late run delays the following ones, which then start as soon as possible to catch up, but one task is never run concurrently with itself.

Summary

  • Timer and TimerTask schedule delayed and repeating work on a single thread; one failing or slow task harms all the others, so treat it as legacy.
  • ScheduledExecutorService provides schedule, scheduleAtFixedRate and scheduleWithFixedDelay, runs on a pool and returns a ScheduledFuture for cancelling and for results.
  • Fixed rate keeps to a start-to-start period (catching up when late); fixed delay waits a fixed gap after each run ends.
  • An exception in a repeating task silently stops it: wrap the body in try/catch and log.
  • Cancel with future.cancel(false) and always shut the scheduler down, or non-daemon threads keep the JVM alive.
  • For calendar-style schedules (daily at 02:00) use cron-based frameworks or compute the next delay with java.time.

Next: Networking Basics, where your programs start talking to other machines.