Using java.util.Timer for Scheduled and Delayed Tasks in Java
This article explains how to use java.util.Timer for one‑time and periodic task scheduling, covering constructors, instance methods, daemon‑thread behavior, handling past dates, negative delays, multiple tasks, and proper shutdown, with complete code examples and execution results.
In many projects you need to run tasks after a delay or at regular intervals, such as automatically generating reports, exporting Excel files, or sending push notifications. The JDK class java.util.Timer provides a simple way to schedule these tasks.
Constructors
Timer() – creates a new timer with a non‑daemon thread.
Timer(boolean isDaemon) – creates a timer whose worker thread can be a daemon.
Timer(String name) – creates a timer with a named thread.
Timer(String name, boolean isDaemon) – creates a named timer that may be a daemon.
Instance methods
cancel() – terminates the timer and discards pending tasks.
purge() – removes cancelled tasks from the queue.
schedule(TimerTask task, Date time) – runs a task at a specific time.
schedule(TimerTask task, Date firstTime, long period) – runs a task repeatedly with a fixed delay.
schedule(TimerTask task, long delay) – runs a task after a delay.
schedule(TimerTask task, long delay, long period) – runs a task after a delay and then repeatedly with a fixed delay.
scheduleAtFixedRate(TimerTask task, Date firstTime, long period) – runs a task at a fixed rate.
scheduleAtFixedRate(TimerTask task, long delay, long period) – runs a task at a fixed rate after an initial delay.
Key observations
When the timer is created with the default constructor, its worker thread is non‑daemon, so the JVM will not exit until all scheduled tasks finish.
Creating a timer with new Timer(true) makes the worker thread a daemon; the JVM may exit as soon as the main thread ends, even if tasks are still pending.
Scheduling with a past Date causes the task to run immediately; a negative delay throws IllegalArgumentException .
Long‑running tasks block the timer’s single thread, delaying subsequent tasks; therefore avoid blocking operations inside a TimerTask .
When many tasks are scheduled, the accumulated execution offset grows because the timer processes tasks sequentially.
Use cancel() on a TimerTask to stop a single task and purge() on the timer to clean up cancelled tasks.
Calling timer.cancel() stops the timer entirely and terminates its worker thread.
Code examples
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import static java.lang.System.currentTimeMillis;
import static java.lang.Thread.currentThread;
import static java.text.MessageFormat.format;
public class Task {
private static final long SECOND = 1000;
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println(format("Program end time: {0}", currentTimeMillis()));
}));
long start = currentTimeMillis();
System.out.println(format("Program start time: {0}", start));
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
long expected = start + 10 * SECOND;
long actual = currentTimeMillis();
long offset = actual - expected;
System.out.println(format("Task runs on thread [{0}], expected [{1}], actual [{2}], offset [{3}]",
currentThread().getName(), expected, actual, offset));
}
}, new Date(start + 10 * SECOND));
}
}The article continues with variations that use daemon timers, schedule tasks with negative delays (which raise an exception), add multiple tasks to illustrate sequential execution, and demonstrate periodic scheduling with schedule versus scheduleAtFixedRate . Finally, it shows how to stop individual tasks, purge cancelled ones, and cancel the whole timer.
Conclusion
java.util.Timer is a practical utility for delayed and periodic execution in Java, but developers must be aware of its single‑threaded nature, daemon‑thread impact on JVM shutdown, and the importance of avoiding long‑running or blocking tasks to maintain timing accuracy.
JD Tech
Official JD technology sharing platform. All the cutting‑edge JD tech, innovative insights, and open‑source solutions you’re looking for, all in one place.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.