Java Timer TimerTask Example

Filed Under: Java

Java 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 TimerTask

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.

Java Timer Example

java timer example, java timer, java timertask, java timertask example

Java 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 uses Object wait and notify methods to schedule the tasks.

Here is a simple program for Java Timer and TimerTask example.

package com.journaldev.threads;

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

public class MyTimerTask extends TimerTask {

    public void run() {
        System.out.println("Timer task started at:"+new Date());
        System.out.println("Timer task finished at:"+new Date());

    private void completeTask() {
        try {
            //assuming it takes 20 secs to complete the task
        } catch (InterruptedException e) {
    public static void main(String args[]){
        TimerTask timerTask = new MyTimerTask();
        //running timer task as daemon thread
        Timer timer = new Timer(true);
        timer.scheduleAtFixedRate(timerTask, 0, 10*1000);
        System.out.println("TimerTask started");
        //cancel after sometime
        try {
        } catch (InterruptedException e) {
        System.out.println("TimerTask cancelled");
        try {
        } catch (InterruptedException e) {


Notice that one thread execution will take 20 seconds but Java Timer object is scheduled to run the task every 10 seconds. Here is the output of the program:

TimerTask started
Timer task started at:Wed Dec 26 19:16:39 PST 2012
Timer task finished at:Wed Dec 26 19:16:59 PST 2012
Timer task started at:Wed Dec 26 19:16:59 PST 2012
Timer task finished at:Wed Dec 26 19:17:19 PST 2012
Timer task started at:Wed Dec 26 19:17:19 PST 2012
Timer task finished at:Wed Dec 26 19:17:39 PST 2012
Timer task started at:Wed Dec 26 19:17:39 PST 2012
Timer task finished at:Wed Dec 26 19:17:59 PST 2012
Timer task started at:Wed Dec 26 19:17:59 PST 2012
Timer task finished at:Wed Dec 26 19:18:19 PST 2012
Timer task started at:Wed Dec 26 19:18:19 PST 2012
TimerTask cancelled
Timer task finished at:Wed Dec 26 19:18:39 PST 2012

The output confirms that if a task is already executing, Timer will wait for it to finish and once finished, it will start again the next task from the queue.

Java Timer object can be created to run the associated tasks as a daemon thread. Timer cancel() method is used to terminate the timer and discard any scheduled tasks, however it doesn’t interfere with the currently executing task and let it finish. If the timer is run as daemon thread, whether we cancel it or not, it will terminate as soon as all the user threads are finished executing.

Timer class contains several schedule() methods to schedule a task to run once at given date or after some delay. There are several scheduleAtFixedRate() methods to run a task periodically with certain interval.

While scheduling tasks using Timer, you should make sure that time interval is more than normal thread execution, otherwise tasks queue size will keep growing and eventually task will be executing always. That’s all for a quick roundup on Java Timer and Java TimerTask.


  1. Ankit Sachan says:

    Hi Pankaj, This may be a late question. My requirement is simple, I am going to execute a Java function, which I don’t know how long it will take to finish. Now I want to let this function run only for 30 min, irrespective it completion status. How it can be achieved.

    1. Krishna Chanakya says:

      For the same purpose I am looking for solutions and I found that it can be done using ExecutorService. Refer this you will understand more clearly.

  2. Roger says:

    I would like to learn Discrete Event Simulation for Wireless Sensor Networks, any recommendation like books, websites or youtube channel… I prefer java programming language

  3. Csaba says:

    Hi Sir,
    Really nice example but for people who want to close things exactly without waiting the 30 seconds on the end
    rises some questions:
    Extended cases/questions:
    1) What happens if we also write timerTask.cancel() after timer.cancel() ?
    I assume even the sixth TimerTask’s run won’t be executed until its end.
    2) How to let run exactly only the first six TimerTask once all of the 12 went into the Timer queue?
    I have no idea
    3) What happens if we simple leave the code out on the end with the waiting of 30000 millis?
    I assume the last current TimerTask will broken by java process end.
    Won’t it?
    4) 5) 6) The same questions for each if we start the java process in the background?

  4. kiyanoosh says:

    hi, thanks for testing but I’ve got a question from you. I from Iran and I want to learn Java can you help me what work I should do?

    1. Avi says:

      Hi bro, the best book i ever read on computers :
      look for it in google : java how to program
      published by : deitel and deitel
      you’ll probably find version 8 or 9 of the book in a pdf, they’re both just fine.
      Btw, i teach people Java a 1 year course, and i have experience of over 25 years.
      All the best (btw, I’m from Israel).

  5. Haroon says:

    How can I queue the Task? e,g how can I only start the task if the very first time it executed successfully

  6. inderjeet says:

    how does the last line print
    after cancelling the timer???

    1. Rajiv Saini says:

      @Inderjeet : The last line is executed because it is part of job (i.e defined in run method) and timer cancel method is used to cancel any scheduled task from executing which has not started. The last line was part of previous task which was started before call of cancel method.

  7. kesahv says:

    Notice that one thread execution will take 20 seconds but Java Timer object is scheduled to run the task every 10 seconds

    what is the reason for above line(why does it take 20 secs instead of 10)?
    please answer me

    1. CM says:

      Look at completeTask, they call Thread.sleep(20000). 20000ms == 20 seconds

  8. suhas says:

    this content is really helpful. I got all information which i want thank you….

  9. rvanitha says:

    how to send email automatically every day in java

    1. Pankaj says:

      Better use cronjob to schedule sending email program to run at specific time.

      1. NitB says:

        JavaMail can be better choice if you want to programmatically generate email content, formatting, attachments etc.

  10. Very informative and nice working example, although you probably should be using more robust scheduled executors available in java.util.concurrent from Java SE 5 as Concurrency utilities.

    1) ==> clearly says:
    “Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn’t require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.

    Implementation note: This class scales to large numbers of concurrently scheduled tasks (thousands should present no problem). Internally, it uses a binary heap to represent its task queue, so the cost to schedule a task is O(log n), where n is the number of concurrently scheduled tasks.”

    2),%20long, long, java.util.concurrent.TimeUnit)

  11. Sahanaa R says:

    Hi Sir,
    I want to run a task every 30 min(4 , 4:30 , 5 , 5:30,…) and i have a timertask for that. The task may or may not exceed 30 min. I understand from your tutorial that the next timer will start only after completion of the previous. But irrespective of the task execution time, i want the task to execute at the 30 min period. Is there a possibility for this.?

  12. Manish says:

    Nice Article. One addition here: To cancel and discard all scheduled task from the queue, cancel() method on Timer object needs to be called.

    1. Pankaj says:

      Yes, you are right. You should always look at existing methods to see what is available for you. It’s more or less like Thread programming.

  13. someone says:

    What if i schedule 2 task with same timer say.

    timer.schedule(new TimerTask1(), today, 2pm);
    timer.schedule(new TimerTask2(), today, 3pm);

    is there any performance issue or it is good way?

    1. po_begins says:

      I don’t think there may be any issues using single timer for running different tasks. I am using a single timer to do the scheduling job (same functionality). If all your tasks are of same functionality, you can use a single Timer class to make the things modular. If all the task are different in behavior, it is your call.

      However a word of caution: If you are calling a cancel() method on a Timer, all the scheduled tasks will get cleared (if any task is running, it will allow the task to get completed) while, if you call a the cancel() method on a TimerTask, that particular task will get cancelled.

      Hope it helps.

      1. Pankaj says:

        Thanks for pitching in and clarifying it.

  14. vinod says:

    Hi, I have got some requirement like i want to run a java program to do some task between two time intervals like 10’o clock to 12’o clock everyday… so please help how to accomplish my requirement… any help is really appreciated..

    1. Pankaj says:

      Check scheduling methods.

  15. seshagiri rao says:

    Hi Sir,

    Excellent tutorial it would be great if you can make a tutorial explaining the concurrency in JavaFx.

    1. Pankaj says:

      I have written a lot about Concurrency in Java. Please use search function and you will find it.

  16. Pawan says:

    Very useful definition Pankaj Sir

    1. Pankaj says:

      Thanks Pavan. Don’t call me Sir, it feels old. 🙂

  17. Kunal says:

    Well written article Pankaj. Programs are very clear to understand.

    1. Pankaj says:

      Thanks Kunal.

  18. Aman Seth says:

    Hi Sir ,
    How to use Day light Saving in java Using Timer Class.

    1. Pankaj says:

      Java internally takes care of DST related changes.

  19. Kunal says:

    Hi Pankaj,

    What if I have 2 task. and task1 should run continuously and task2 should run between 6pm to 10pm.
    If you can provide me with an logic, it will be very helpful.

  20. Rashmit says:

    Hi Pankaj,

    The technical content and no-nonsense details for given topic makes your post distinct & joy to read. Its great to know someone has both – Knowledge of Java & Ability in expressing this knowledge… GOD Bless You n Keep posting such wonderful write up..

    1. Pankaj says:

      Thanks Rashmit, I appreciate it.

  21. SAchin says:

    Can it be possible if one existing task running, and other task is checking after 30 min existing task is done or not using timer

  22. Ratul says:

    Will a timer scheduled to run every 24 hours run if server stops or is restarted?

    1. Pankaj says:

      If it’s running on server and it’s terminated, obviously the Timer itself gets terminated. But you can configure it to start when server starts.

      1. Ratul says:

        Can you provide more details on how to configure it to start when server restarts?

  23. savurirjan says:

    without timer we execute the task in certain interval. please provide answer

    1. Pankaj says:

      I didn’t understood your question.

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content