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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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:
1 2 |
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
. Therun
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?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package com.crunchify.tutorials; import java.util.Timer; import java.util.TimerTask; import java.awt.Toolkit; /** * Author: Crunchify.com */ public class CrunchifyTimerTaskExample { Toolkit toolkit; Timer timer; public CrunchifyTimerTaskExample() { toolkit = Toolkit.getDefaultToolkit(); timer = new Timer(); timer.schedule(new CrunchifyReminder(), 0, // initial delay 1 * 1000); // subsequent rate } class CrunchifyReminder extends TimerTask { int loop = 5; public void run() { if (loop > 0) { toolkit.beep(); System.out.format("Knock Knock..!\n"); loop--; } else { toolkit.beep(); System.out.format("\nThat's it.. Done..!"); timer.cancel(); } } } public static void main(String args[]) { new CrunchifyTimerTaskExample(); System.out.format("Task scheduled..!%n \n"); } } |
Result:
1 2 3 4 5 6 7 8 9 |
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’srun
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.