Java - Scheduling tasks using java.util.Timer

[Updated: Feb 7, 2017, Created: Aug 10, 2016]

java.util.Timer provides a way to schedule the tasks (one or more tasks).

Timer starts a new background thread and executes the submitted tasks in that new thread.

The timer can repeat the tasks periodically based on a provided time period.

This class is thread-safe, i.e. multiple threads can use a single Timer object without taking care of synchronization themselves.

Scheduling Task with Timer

The overloaded Timer constructors just take trivial info i.e. timer's name and isDaemon. There's a no arg constructor available as well.

After creating Timer instance, we just need to call one of the following schedule(..) methods to submit tasks:

Initial Delay

The moment we call one of the above schedule methods, timer wait for the initial delay before executing the task.

Fixed-delay execution

Start of each period is always recorded at the beginning of each task execution. Subsequent tasks are scheduled at the end of each period. If an execution is delayed for any reason (such as garbage collection or other o.s. activity, the start of the corresponding period is also delayed.

Task execution itself should be very quick, possibly of few milli-seconds. In case if tasks run longer than specified period, they will execute immediately after one another.

These methods should be used where frequency of some task is important e.g. blinking of a cursor etc.

Fixed-rate execution

Start of each period is recorded consecutively without any delay, regardless of if a task starts late (because of JVM or O.S activities).

These methods should be used where absolute timing is important e.g. sending some message every hour, archiving log files at end of the week etc.

The TimerTask class

You must have noticed the TimerTask in above schedule method parameters. This class
- is an abstract class,
- implements Runnable,
- and has only one abstract method run(), which executes our provided task.

How Timer does multi-threading?

When a Timer instance is created, a background thread is created and started i.e. it's start() method is called. This thread is a Timer's nested class: TimerThread (we don't have to remember the name by the way, we mentioned it for further explanation and as a convenient reference on this page).

This new spawned thread monitors (poll) a queue containing submitted task.

As soon as we submit a task this thread gets and removes that task from the queue, wait for the initial delay to elapse then executes the TimerTask's run method (another new thread is not created but instad is called directly)

That means all tasks are executed sequentially within the same thread (TimerThread). Tasks should finish quickly, otherwise it will delay the execution of subsequent tasks.

If a task might take a long time (longer than provided delay or periodicity) then we should spawn a new thread within the task's run() method.

By default, the TaskThread instance does not run as a daemon thread, so it will keep an application from terminating even all thask finish executing. If we want to terminate a timer execution thread immediately, Timer#cancel() must be called.

Scheduling multiple tasks

For the same instance of Timer there's only one background thread (TimerThread), which will handle all Timer's schedule method calls. That means all tasks will run sequentially.

Also we should provide different instances of the TimerTask, submitting the same instance multiple times will cause IllegalStateException(Task already scheduled or cancelled)

Example Project:

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.0.4

Java Timer Example Select All Download
  • java-util-timer-examples
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also