Tutorial

Java Timer TimerTask Example

Published on August 3, 2022
author

Pankaj

Java Timer TimerTask Example

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 {

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

    private void completeTask() {
        try {
            //assuming it takes 20 secs to complete the task
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    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 {
            Thread.sleep(120000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        timer.cancel();
        System.out.println("TimerTask cancelled");
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 7, 2013

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

- savurirjan

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 6, 2014

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

    - Ratul

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      June 27, 2014

      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

      - SAchin

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        July 11, 2014

        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…

        - Rashmit

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          August 7, 2014

          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.

          - Kunal

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            September 15, 2014

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

            - Aman Seth

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              November 17, 2014

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

              - Kunal

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                January 2, 2015

                Very useful definition Pankaj Sir

                - Pawan

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  March 31, 2015

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

                  - seshagiri rao

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    May 25, 2015

                    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…

                    - vinod

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.