Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
java.time.LocalTime Class in Java
Next article icon

Java.util.TimerTask class in Java

Last Updated : 26 Apr, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

TimerTask is an abstract class defined in java.util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden. The run method is implicitly invoked when a timer object schedules it to do so. 

Note: An instance of TimerTask class is used to define a task the needs to run periodically. 

Constructors:

  • TimerTask(): Creates a new timer task

Declaration:

public abstract class TimerTask         extends Object         implements Runnable

Methods:

  • cancel(): java.util.TimerTask.cancel() Cancels this timer task 
  • Syntax:
public boolean cancel() Returns: true if this task is scheduled for one-time execution and has not yet run, or this task is scheduled for repeated execution.  Returns false if the task was scheduled for one-time  execution and has already run, or if the task was never scheduled,  or if the task was already cancelled.
  • run(): java.util.TimerTask.run() The action to be performed by this timer task 
  • Syntax:
public abstract void run() Description: The action to be performed by this timer task
  • scheduledExecutionTime(): java.util.TimerTask.scheduledExecutionTime() Returns the scheduled execution time of the most recent actual execution of this task 
  • Syntax:
public long scheduledExecutionTime() Returns:  the time at which the most recent execution of this task was  scheduled to occur, in the format returned by Date.getTime().  The return value is undefined if the task has yet to  commence its first execution

Methods inherited from class java.lang.Object

  • clone
  • equals
  • finalize
  • getClass
  • hashCode
  • notify
  • notifyAll
  • toString
  • wait

Java program to demonstrate usage of TimerTask class

Java




// Java program to demonstrate
// working of TimerTask class
import java.util.Timer;
import java.util.TimerTask;
 
class Helper extends TimerTask
{
    public static int i = 0;
    public void run()
    {
        System.out.println("Timer ran" + ++i);
        if(i == 4)
        {
            synchronized(Test.obj)
            {
                Test.obj.notify();
            }
        }
    }
     
}
 
 
public class Test
{
    public static Test obj;
    public static void main(String[] args) throws InterruptedException
    {
        obj = new Test();
         
        // creating an instance of timer class
        Timer timer = new Timer();
         
        // creating an instance of task to be scheduled
        TimerTask task = new Helper();
         
        // scheduling the timer instance
        timer.schedule(task, 1000, 3000);
         
        // fetching the scheduled execution time of
        // the most recent actual execution of the task
        System.out.println(task.scheduledExecutionTime());
         
        synchronized(obj)
        {
            //this thread waits until i reaches 4
            obj.wait();
        }
         
        //canceling the task assigned
        System.out.println("Cancel the timer task: " + task.cancel());
         
        // at this point timer is still running
        // without any task assigned to it
     
        // canceling the timer instance created
        timer.cancel();
    }
}
 
 

Output:

1495715853591 Timer ran 1 Timer ran 2 Timer ran 3 Timer ran 4 Cancel the timer task: true

Reference:

  • Oracle


Next Article
java.time.LocalTime Class in Java

M

Mayank Kumar
Improve
Article Tags :
  • Java
  • Misc
Practice Tags :
  • Java
  • Misc

Similar Reads

  • Java.util.Timer Class in Java
    Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions. Each timer object is associated with a background thread that is responsi
    6 min read
  • java.time.LocalTime Class in Java
    Java is the most popular programming language and widely used programming language. Java is used in all kinds of applications like mobile applications, desktop applications, web applications. As in Java, java.time.LocalTime class represents time, which is viewed as hour-minute-second. This class is
    5 min read
  • java.time.OffsetTime Class in Java
    Java OffsetTime class is an immutable date-time object that represents a time, often viewed as hour-minute-second offset. OffsetTime class represents a time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 18:30:45+08:00, often viewed as an hour-minute-second-offset. This c
    7 min read
  • java.time.Period Class in Java
    The Period Class in Java class obtains a quantity or amount of time in terms of years, months and days. The time obtained is a date-based amount of time in the ISO-8601 calendar system, such as '4 years, 5 months, and 6 days. The units which are supported for a period are YEARS, MONTHS, and days. Al
    5 min read
  • Java.lang.Runtime class in Java
    In Java, the Runtime class is used to interact with Every Java application that has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method. Methods of Java
    6 min read
  • java.time.ZoneOffset Class in Java
    A time-zone offset is that the amount of your time that a time-zone differs from Greenwich/UTC. This is often usually a hard and fast number of hours and minutes. From the time package of java, ZoneOffset class is employed to represent the fixed zone offset from UTC zone and inherits the ZoneId clas
    3 min read
  • java.time.Clock Class in Java
    Java Clock class is present in java.time package. It was introduced in Java 8 and provides access to current instant, date, and time using a time zone. The use of the Clock class is not mandatory because all date-time classes also have a now() method that uses the system clock in the default time zo
    3 min read
  • java.time.LocalDateTime Class in Java
    java.time.LocalDateTime class, introduced in Java 8, represents a local date-time object without timezone information. The LocalDateTime class in Java is an immutable date-time object that represents a date in the yyyy-MM-dd-HH-mm-ss.zzz format. It implements the ChronoLocalDateTime interface and in
    4 min read
  • java.time.OffsetDateTime Class in Java
    Java is the most popular programming language and widely used programming language. Java is used in all kind of application like mobile application, desktop application, web application. In this Java java.time.OffsetDate, Time class is imported which is an immutable representation of a date-time wit
    4 min read
  • java.time.LocalDate Class in Java
    Java is the most popular programming language and widely used programming language. Java is used in all kind of application like as mobile application, desktop application, web application. In this Java java.time.LocalDate class is imported which represents to display the current date. java.time: It
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences