Java Timer, TimerTask, Reminder Class Tutorial with Example

java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals.

java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.

Timer class is thread safe and multiple threads can share a single Timer object without need for external synchronization. Timer class uses java.util.TaskQueue to add tasks at given regular interval and at any time there can be only one thread running the TimerTask, for example if you are creating a Timer to run every 10 seconds but single thread execution takes 20 seconds, then Timer object will keep adding tasks to the queue and as soon as one thread is finished, it will notify the queue and another thread will start executing.

Java Timer Class

Timer class uses Object wait and notify methods to schedule the tasks. TimerTask is an abstract class and we inherit it to provide concrete implementation. TimerTask class implements Runnable interface so it is a thread and hence your implementation of TimerTask is also a thread.

Very simple Timer and TimerTask Example: Task executes once 5 seconds have passed.

package com.crunchify.tutorials;

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

/**
 * Author: Crunchify.com
 */

public class CrunchifyTimerTaskExample {
        Timer timer;

        public CrunchifyTimerTaskExample(int seconds) {
                timer = new Timer();
                timer.schedule(new CrunchifyReminder(), seconds * 1000);
        }

        class CrunchifyReminder extends TimerTask {
                public void run() {
                        System.out.format("Timer Task Finished..!%n");
                        timer.cancel(); // Terminate the timer thread
                }
        }

        public static void main(String args[]) {
                new CrunchifyTimerTaskExample(5);
                System.out.format("Task scheduled.. Now wait for 5 sec to see next message..%n");
        }
}

Result:

Task scheduled.. Now wait for 5 sec to see next message..
Time's up!

This simple program illustrates the following basic parts of implementing and scheduling a task to be executed by a timer thread:

  • Implement a custom subclass of TimerTask. The run method contains the code that performs the task. In this example, the subclass is named CrunchifyReminder.
  • Create a thread by instantiating the Timer class.
  • Instantiate the TimerTask object (new CrunchifyReminder()).
  • Schedule the timer task for execution.

How can I perform this TimerTask Repeatedly?

package crunchify.com.tutorials;

import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;

/**
 * Author: Crunchify.com
 * Java Timer and TimerTask - Reminder Class Tutorials
 */

public class CrunchifyTimerTaskExample {

        // Toolkit This class is the abstract superclass of all actual implementations of the Abstract Window Toolkit.
        // Subclasses of the Toolkit class are used to bind the various components to particular native toolkit implementations.
    Toolkit toolkit;

    // Timer A facility for threads to schedule tasks for future execution in a background thread.
        // Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.
    Timer timer;

    public CrunchifyTimerTaskExample() {
        toolkit = Toolkit.getDefaultToolkit();
        timer = new Timer();

        // schedule() Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.
                // Subsequent executions take place at approximately regular intervals separated by the specified period.
        timer.schedule(new CrunchifyReminder(), 0, // initial delay
                1 * 1000); // subsequent rate
    }

    // TimerTask A task that can be scheduled for one-time or repeated execution by a Timer.
        // A timer task is not reusable. Once a task has been scheduled for execution on a Timer or cancelled,
        // subsequent attempts to schedule it for execution will throw IllegalStateException.
    class CrunchifyReminder extends TimerTask {
        int loop = 5;

        public void run() {
            if (loop > 0) {
                // beep() Emits an audio beep depending on native system settings and hardware capabilities.
                toolkit.beep();
                System.out.format("Knock Knock..!\n");
                loop--;
            } else {
                toolkit.beep();
                System.out.format("\nThat's it.. Done..!");

                // cancel() Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated,
                                // its execution thread terminates gracefully, and no more tasks may be scheduled on it.
                timer.cancel();
            }
        }
    }

    public static void main(String args[]) {
        new CrunchifyTimerTaskExample();
        System.out.format("Task scheduled..!%n \n");
    }
}

Result:

Task scheduled..!

Knock Knock..!
Knock Knock..!
Knock Knock..!
Knock Knock..!
Knock Knock..!

That's it.. Done..!

By default, a program keeps running as long as its timer threads are running. You can terminate a timer thread in four ways:

  • Invoke cancel on the timer. You can do this from anywhere in the program, such as from a timer task’s run method.
  • Make the timer’s thread a “daemon” by creating the timer like this: new Timer(true). If the only threads left in the program are daemon threads, the program exits.
  • After all the timer’s scheduled tasks have finished executing, remove all references to the Timer object. Eventually, the timer’s thread will terminate.
  • Invoke the System.exit method, which makes the entire program (and all its threads) exit.

The post Java Timer, TimerTask, Reminder Class Tutorial with Example appeared first on Crunchify.