Timer and TimerTask: Scheduling Future Actions
Sometimes you want your code to run at a specific time or repeat at regular intervals—like a background sync, a reminder, or a simple clock. In Java, we use the Timer (the scheduler) and TimerTask (the action) classes to achieve this.
1. The Core Components
TimerTask: An abstract class that represents the task you want to perform. You must create a subclass (or an anonymous class) and override therun()method.Timer: The facility that manages the background thread used to execute the tasks.
2. Basic Scheduling Methods
| Method | Description |
|---|---|
schedule(task, delay) |
Runs the task once after a delay (in milliseconds). |
schedule(task, time) |
Runs the task once at a specific Date/Time. |
schedule(task, delay, period) |
Runs the task after a delay, then repeats it every period milliseconds. |
cancel() |
Stops the timer or the specific task. |
3. Creating a TimerTask
You can define your task as a separate class or as an Anonymous Class for quick one-off jobs.
import java.util.Timer;
import java.util.TimerTask;
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Beep! Task executed.");
}
};
// Run after 3 seconds
timer.schedule(task, 3000);
💻 Full Practical Example: The Countdown Timer
Copy this code to see a repeating task that eventually stops itself:
import java.util.Timer;
import java.util.TimerTask;
public class Countdown {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
int seconds = 5;
@Override
public void run() {
if (seconds > 0) {
System.out.println("Time remaining: " + seconds + "s");
seconds--;
} else {
System.out.println("Blast off! 🚀");
timer.cancel(); // Stop the timer thread
}
}
};
// Start immediately (0), repeat every 1 second (1000ms)
timer.scheduleAtFixedRate(task, 0, 1000);
}
}
4. Key Differences: schedule vs scheduleAtFixedRate
schedule: Best for tasks that care about the delay between executions. If one task is late, the next one is pushed back.scheduleAtFixedRate: Best for tasks that care about the absolute time (like a clock). It tries to "catch up" if a task is delayed to keep the overall frequency consistent.
⚠️ Important Note on Threads
A Timer creates a separate background thread. If you are building a GUI application (like JavaFX), remember that TimerTask runs on its own thread, not the UI thread. To update the UI, you would need to wrap your changes in Platform.runLater().
💡 Challenge: The Periodic Logger
- Create a
Timerthat runs every 5 seconds. - Inside the
run()method, print the current time (usingLocalTime.now()). - Have the program stop automatically after it has printed 5 times.