Using Timer Class to Schedule Tasks

Learn how to use the Timer and the TimerTask classes to implement simple task scheduling for your application.

“Humor is reason gone mad.”
― Groucho Marx

1. Introduction

Scheduling tasks to run is a need which sometimes arises in a java program. Maybe you want to run periodic cleanup of some resource. Or check on the status of some job. Or maybe fetch a URL which might not be available the first time.

The Timer class provides a very simple implementation of such a scheduler. Let us learn how to use it.

2. Defining Your Task

The Timer class requires that the application code extend TimerTask class to run the task. The TimerTask in turn implements the Runnable interface. Here is a simple class which extends the TimerTask. You just have to define the run() method to do whatever you want.

public class MyTask extends TimerTask
{
    private String name;

    public MyTask(String name) {
        this.name = name;
    }

    public void run() {
        System.out.println(Thread.currentThread() + " executing " +
                           this.name + " [" +
                           new Date() + "]");
    }
}

3. Run a Task

Next you need to create a Timer instance as follows:

Timer timer = new Timer();

Simple as pie. This instance has now started a thread which runs in the background ready to execute any tasks you may throw at it.

Let us throw one at it. Here we request scheduling of a task at a particular time in the future. The task executes once at the specified time and finishes up.

timer.schedule(new MyTask("john"), new Date(new Date().getTime() + 5000));

Here is the output:

Thread[Timer-0,5,main] executing john [Mon Apr 24 18:04:56 IST 2017]

4. Using an Instant to Create a Date

Instead of the awkward way of defining a Date object 5 secs in the future as shown above, you can use the Instant class as shown below. Create a current Instant, add 5 seconds to it and convert it to a Date.

timer.schedule(new MyTask("john"), Date.from(Instant.now().plusSeconds(5)));

5. Scheduling a Repeating Task

Wait. There is more! The Timer class also allows you to schedule a repeating task. In the code below we schedule a task executing every 3 secs (perhaps to check up on our stock portfolio).

timer.schedule(new MyTask("jack"), 0, 3000);

And here is task faithfully running every 3000 milliseconds as ordered.

Thread[Timer-0,5,main] executing jack [Mon Apr 24 18:12:36 IST 2017]
Thread[Timer-0,5,main] executing jack [Mon Apr 24 18:12:39 IST 2017]
Thread[Timer-0,5,main] executing jack [Mon Apr 24 18:12:42 IST 2017]

All that with a couple of lines to add scheduling to your application, isn’t that nifty?

6. Starting with an Initial Delay

So you want to schedule your job for repeated executing, but with an initial delay? You are covered! Here we start the task 1 second later but run it every 500 milliseconds.

timer.schedule(new MyTask("joe"), 1000, 500);

See that neat little bugger chugging along? Life is easy.

Thread[Timer-0,5,main] executing joe [Mon Apr 24 18:18:34 IST 2017]
Thread[Timer-0,5,main] executing joe [Mon Apr 24 18:18:35 IST 2017]
Thread[Timer-0,5,main] executing joe [Mon Apr 24 18:18:35 IST 2017]
Thread[Timer-0,5,main] executing joe [Mon Apr 24 18:18:36 IST 2017]

7. Caveats

The Timer class is a very simple class meant to be used for simple scheduling within an application. For more complex requirements such as thread pools, the ExecutorService class is more appropriate.

Summary

And that presented some usage patterns for implementing simple task scheduling within an application. The application needs to override the run() method of the TimerTask class and can schedule it for future execution, possibly for repeated runs.

Leave a Reply

Your email address will not be published. Required fields are marked *