Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java Timer/TimerTask example


How to use Java Timer and TimerTask to schedule tasks execution at specified time or in repeated manner? In this post we’re going to show cooperation of these two classes.


Both Timer and TimerTask classes have been designed to work together to provide simple scheduling mechanism. The TimerTask is just a class build on top of Runnable interface and provides two methods:

  • boolean cancel()
    To cancel the task.
  • long scheduledExecutionTime()
    Returns the scheduled execution time of the most recent actual execution of this task.

The method have to be implemented by the task itself, as we do here.

Timer is the scheduler here. It has more methods, but they generally can be grouped as follows:

  • void schedule()
    Schedule a task at specified time for one-time execution.
  • void scheduleAtFixedRate()
    Schedule a task for repeated execution.

In the following example we’re going to create a Web Crawler task and execute it every 200 milliseconds, but the first execution will be delayed by 100 milliseconds. Then, after 2 seconds we’re going to stop the timer, which automatically stops all scheduled tasks:


import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class TimerExample {

    private static class WebClawlerTask extends TimerTask {

        private int count = 0;

        public void run() {
            System.out.println("Crawling the web count: " + ++count);

    public static void main(String[] args) throws InterruptedException {
        Timer timer = new Timer();
        int delay = 100;
        int period = 200;
        timer.scheduleAtFixedRate(new WebClawlerTask(), delay, period);


        System.out.println("Stopping the timer.");

And here’s the result of running the above code:

Crawling the web count: 1
Crawling the web count: 2
Crawling the web count: 3
Crawling the web count: 4
Crawling the web count: 5
Crawling the web count: 6
Crawling the web count: 7
Crawling the web count: 8
Crawling the web count: 9
Crawling the web count: 10
Crawling the web count: 11
Stopping the timer.

It’s a nice and simple way to run a background job. :-)

In the next post we’re going to show how to apply java.util.concurrent for scheduling.

Share with the World!