Java Timer Tutorial

The Java Timer class is a utility from the java.util package. The Timer class provides a method call that can be used by a thread to schedule a task.

A task can be scheduled by a Timer to run once or repeat N times. A timer is associated with a thread that manages it’s execution.

Schedule Once

The simplest thing we can do with a Timer is to schedule a task once.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public static void scheduleOnce() {
    TimerTask task = new TimerTask() {
        public void run() {
            System.out.println("Task Running at: " + new Date());
        }
    };

    Timer timer = new Timer("Timer");
    long delay = 2000L;
    timer.schedule(task, delay);
}

Above, we create an instance of the TimerTask class. Next we create our Timer instance, and schedule the timer task to execute once, after a 2 millisecond delay.

Behind the scenes the timer is associated with a background thread that executes the task.

Schedule Repeatedly At An Interval

The timer can also be used to schedule a timer task to execute repeatedly at a given interval.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public static void scheduleRepeatedly() {
    TimerTask repeatedTask = new TimerTask() {
        public void run() {
            System.out.println("Repeated Task Running at: " + new Date());
        }
    };

    Timer timer = new Timer("Timer");
    long delay = 2000L;
    long period = 1000L;

    timer.scheduleAtFixedRate(repeatedTask, delay, period);
}

Above the task is scheduled repeatedly after a 2 millisecond delay, to execute every 1 millisecond.

Schedule A Daily Task

We can also schedule the task to run at different times for example daily, weekly etc.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public static void scheduleDailyTask() {
    TimerTask repeatedTask = new TimerTask() {
        public void run() {
            System.out.println("Task Running at: " + new Date());
        }
    };
    Timer timer = new Timer("Timer");
    long delay = 2000L;
    long daily = 1000L * 60L * 60L * 24L;
    timer.scheduleAtFixedRate(repeatedTask, delay, daily);
}

Cancel The TimerTask

We can stop a timer in a number of ways, first we can let the timer task cancel itself.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public static class CancellableTask extends TimerTask {
    private int count = 1;

    @Override
    public void run() {
        System.out.println("Task Running at: " + new Date() + ", with count: " + count);
        if(count==10) {
            cancel();
        }
        count++;
    }
}

The above task will cancel itself when the count variable has the value 10. Note that this only cancels the timer task and not the timer.

Cancel The Timer

We can cancel both the task and the timer by using the cancel method of the timer class.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public static void main(String[] args) throws Exception {
    TimerTask repeatedTask = new TimerTask() {
        public void run() {
            System.out.println("Repeated Task Running at: " + new Date());
        }
    };

    Timer timer = new Timer("Timer");
    long delay = 1000L;
    long period = 1000L;

    timer.scheduleAtFixedRate(repeatedTask, delay, period);

    Thread.sleep(10000);
    timer.cancel();
}

Use The ExecutorService Instead

The Java ExecutorService can also be used to schedule a TimerTask.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public static void scheduleWithExecutorService() throws Exception {
    TimerTask repeatedTask = new TimerTask() {
        public void run() {
            System.out.println("Task Running at: " + new Date());
        }
    };

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    long delay  = 1000L;
    long period = 1000L;

    executor.scheduleAtFixedRate(repeatedTask, delay, period, TimeUnit.MILLISECONDS);

    Thread.sleep(10000);
    executor.shutdown();
}

Conclusion

In this tutorial we examined the Timer and TimerTask classes in Java.