Java Timer Example
November 17, 2023
On this page, we will learn to use Timer
in our Java application.
1.
Timer
schedules a task to run at a given time, once or repeatedly.
2.
Timer
runs associated with a thread. It can also run in background as daemon thread.
3. To associate
Timer
with daemon thread, it has a constructor with boolean value. It also provides argument to specify thread name.
4.
Timer
schedules task with fixed delay as well as fixed rate.
5. In fixed delay, if any execution is delayed by System GC or something else, the other execution will also be delayed and every execution is delayed corresponding to previous execution. In fixed rate, if any execution is delayed, then 2-3 execution happens consecutively to cover the fixed rate corresponding to the first execution start time.
6.
Timer
provides cancel()
method to cancel a Timer
. When this method is called, Timer
is terminated.
7. In Java 5,
Timer
has been provided with purge()
method which purges all canceled task from the queue.
8.
Timer
executes only the task that implements TimerTask
.
1. Instantiate Timer
Find the constructors to instantiateTimer
.
Timer(): Create a
Timer
instance.
Timer(boolean isDaemon) : If true argument is passed, then it runs associated with a daemon thread.
Timer(String name): It runs with thread with given thread name.
Timer(String name, boolean isDaemon) : If daemon value is true, then timer runs associated with a daemon thread with given tread name.
2. Create a Task using TimerTask
Timer
executes a TimerTask
implementation. TimerTask
can be executed one time or repeatedly. To perform the action, we need to override its run()
method.
public class MyTimerTask extends TimerTask { @Override public void run() { //perform action } }
3. How to Cancel a Timer
To cancel or stop aTimer
, this class provides cancel()
method. This method when called, terminates the Timer
and discards all scheduled tasks. Alternatively we can also call System.exit(0)
. Find the code snippet to cancel the Timer
.
try { Thread.sleep(5000); //Main thread sleep for 5 seconds to finish timer. } catch (InterruptedException e) { e.printStackTrace(); } finally { timer.cancel(); // System.exit(0) }
4. Difference between Timer schedule() and scheduleAtFixedRate()
Find the difference between Timerschedule()
and scheduleAtFixedRate()
methods.
schedule() : It repeats a task with a given delay corresponding to previous execution. Suppose a task has been scheduled to execute after every 2 seconds and suppose E denotes execution and W denotes waiting of one second. The three consecutive executions can be represented as below.
EWWEWWE
The total delay is of 4 seconds in three execution.
This means that first execute(E), then wait for 2 seconds(WW), then execute(E) then wait for two seconds(WW) then execute(E). Now suppose if there is a delay of two seconds just before second execution because of System GC (garbage collector) or any other reason, then consecutive execution will be as below.
EWWWWEWWE
Here the three executions take total delay of 6 seconds.
scheduleAtFixedRate() : It repeats a task with a given fixed rate corresponding to first execution. In normal situation there is no difference between
schedule()
and scheduleAtFixedRate()
. But when there is a delay in any execution because of System GC (garbage collector) or any other reason, then next 2, 3 executions can happen consecutively to recover the fixed rate corresponding to first execution. Now we will take again the same scenario of where second execution gets two seconds delay because of System GC. In this case, the repeating can be represented as below.
EWWWWEE
The total delay time is 4 seconds only.
5. Timer schedule() for One Time Execution
Find the schedule()
method to schedule a task on a given date or with a given delay that will execute only once.
schedule(TimerTask task, Date time): Here task is the instance of
TimerTask
and time is the Date
instance at which task will be executed.
schedule(TimerTask task, long delay) : Task will start after given delay in milliseconds.
Find the example.
ScheduleDemoOne.java
package com.concretepage; import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class ScheduleDemoOne { public static void main(String[] args) { Timer timer = new Timer("exam"); TaskOne task = new TaskOne(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, 3);//added 3 seconds to current time Date startTime = calendar.getTime(); System.out.println("Writing answer..."); timer.schedule(task, startTime); //Task will be executed after 3 seconds try { Thread.sleep(5000); //Main thread sleep for 5 seconds to finish timer. } catch (InterruptedException e) { e.printStackTrace(); } finally { timer.cancel(); // System.exit(0) } System.out.println("Timer stopped."); } } class TaskOne extends TimerTask { @Override public void run() { System.out.println("Time Up."); } }
Writing answer... Time Up. Timer stopped.
6. Timer schedule() for Repeating Execution
schedule()
can schedule a repeating task with a given period. The given period is counted from the previous execution. If an execution is delayed then all the subsequent execution will be delayed. To start a repeating task with an interval, we need to pass following arguments.
schedule(TimerTask task, Date firstTime, long period): Task will start on the given date and will repeat with given period.
schedule(TimerTask task, long delay, long period): Task will start with given delay and will repeat with given period.
Find the example.
ScheduleDemoTwo.java
package com.concretepage; import java.util.Timer; import java.util.TimerTask; public class ScheduleDemoTwo { public static void main(String[] args) { Timer timer = new Timer("taskthread"); TaskTwo task = new TaskTwo(1); //passed counter as 1 int startTime = 3; //in seconds System.out.println("Task will start after "+ startTime +" seconds." ); timer.schedule(task, startTime*1000, 2000); //start after 3 seconds and repeat after every 2 seconds try { Thread.sleep(15000); //Main thread sleep for 15 seconds. } catch (InterruptedException e) { e.printStackTrace(); } finally { timer.cancel(); } System.out.println("Timer stopped."); } } class TaskTwo extends TimerTask { private int counter; public TaskTwo(int counter) { this.counter = counter; } @Override public void run() { System.out.println("Counter " + counter++ +": Doing task..."); } }
Task will start after 3 seconds. Counter 1: Doing task... Counter 2: Doing task... Counter 3: Doing task... Counter 4: Doing task... Counter 5: Doing task... Counter 6: Doing task... Counter 7: Doing task... Timer stopped.
7. Timer scheduleAtFixedRate() for Repeating Execution
scheduleAtFixedRate()
schedules a repeating task with given period. If any execution is delayed then it executes 2-3 tasks consecutively to maintain the fixed rate corresponding to start time.
scheduleAtFixedRate(TimerTask task, Date firstTime, long period) : Task will start on the given date and will repeat with given period.
scheduleAtFixedRate(TimerTask task, long delay, long period) : Task will start with given delay and will repeat with given period.
Find the example.
ScheduleAtFixedRateDemo.java
package com.concretepage; import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class ScheduleAtFixedRateDemo { public static void main(String[] args) { Timer timer = new Timer("stopwatch"); MyTask task = new MyTask(); Calendar calendar = Calendar.getInstance(); int second = 3; calendar.add(Calendar.SECOND, second);//added 3 seconds to current time Date startTime = calendar.getTime(); System.out.println("Bell will start ringing after "+ second +" seconds"); timer.scheduleAtFixedRate(task, startTime, 2000);// start after 3 seconds and repeat after every 2 seconds. try { Thread.sleep(10000); //Main thread sleep for 10 seconds to finish timer. } catch (InterruptedException e) { e.printStackTrace(); } finally { timer.cancel(); } System.out.println("Timer stopped."); } } class MyTask extends TimerTask { @Override public void run() { System.out.println("Ringing Bell..."); } }
Bell will start ringing after 3 seconds Ringing Bell... Ringing Bell... Ringing Bell... Ringing Bell... Timer stopped.