Java Timer example

Timer is an utility class which can be used to schedule tasks on specific time or repeatedly.
Lets say, you are developing an banking application and there is need to process the data at 7 PM evening daily. You can easily schedule task using Timer class.
For creating a task, you need to extends TimerTask and Timer can be used to set time for the task.
TimerTask : It is task which will be executed at specific time.
Timer : It is utility class which is used to set time for the task.
Timer class is thread safe , so multiple threads can share one timer object. Timer class internally uses java.util.TaskQueue to manage task internally. Only one thread can execute timer task at a time.

For example:
You are executing task in every 5 secs but actual execution itself is taking 10 seconds, then subsequent task will be added to queue and as soon as current execution completes, it will notify and another thread will start executing the task.
When you debug timer object, it looks something like this.

Java timer example
Methods for scheduling task:
There are several methods in timer class that can be used to schedule.

For one time execution:

For repeated execution:

For executing task at particular time:
For executing task at particular time repeatedly:

Example:

For one time exectution:

Create a class MyTimerTask.java

In above class, we are using timer.cancel() to stop the timer thread. When you call timer.cancel() method, it completes execution of current thread and discards all other threads which are in queue.

Create a class TimerMain.java.

When you run above program, you will get following output:

For repeated execution:

Create a class MyTimerTask.java

Create a class TimerMain.java.
When you run above program, you will get following output:

For executing task at particular time:

Create a class MyTimerTask.java

Create a class TimerMain.java.
When you run above program, you will get following output:

Was this post helpful?

Comments

Leave a Reply

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