Skip to main content

Timer & TimerTask

The java.util.Timer and java.util.TimerTask classes provide a built-in mechanism for developers to schedule tasks to run in a background thread. You can schedule a task to run once at a specific time, or repeatedly at a regular interval.


1. The TimerTask Class

A TimerTask represents the actual job or task that needs to be executed. It is an abstract class that implements the Runnable interface.

  • To use it, you must create a subclass of TimerTask and override its run() method with the code you want to execute.

2. The Timer Class

The Timer class is the facility that schedules tasks for future execution. Under the hood, each Timer object uses a single background thread that executes all of the timer's tasks sequentially.


Example: Scheduling a Task

In this example, we will schedule a task to run after a delay, and then have it repeat every few seconds.

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

// Step 1: Create a class that extends TimerTask
class MyScheduledTask extends TimerTask {

int count = 1;

// Step 2: Override the run method
@Override
public void run() {
System.out.println("Execution #" + count + " at " + new Date());
count++;

// Terminate the timer after 5 executions
if (count > 5) {
System.out.println("Task completed. Cancelling timer.");
this.cancel(); // Cancels this specific task
}
}
}

public class LabTimer1 {

public static void main(String[] args) {
System.out.println("Program Started at " + new Date());

// Step 3: Create the Timer instance
Timer timer = new Timer();

// Step 4: Create the Task instance
TimerTask myTask = new MyScheduledTask();

// Step 5: Schedule the task
long delay = 2000; // 2 seconds delay before first execution
long period = 1000; // 1 second interval between subsequent executions

// schedule(Task, Delay, Period)
timer.schedule(myTask, delay, period);
}
}

Output:

Program Started at Wed Oct 25 10:00:00 UTC 2023
Execution #1 at Wed Oct 25 10:00:02 UTC 2023
Execution #2 at Wed Oct 25 10:00:03 UTC 2023
Execution #3 at Wed Oct 25 10:00:04 UTC 2023
Execution #4 at Wed Oct 25 10:00:05 UTC 2023
Execution #5 at Wed Oct 25 10:00:06 UTC 2023
Task completed. Cancelling timer.

[!WARNING] While Timer and TimerTask are useful for simple scheduling, modern Java applications (especially enterprise applications) generally prefer using the ScheduledExecutorService (from the java.util.concurrent package), as it uses thread pools and handles runtime exceptions inside tasks much more gracefully than Timer does.