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.Period Class in Java
Next article icon

Java.util.Timer Class in Java

Last Updated : 14 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 responsible for the execution of all the tasks of a timer object. 
Note: 

  • Timer class is thread-safe.
  • Timer class uses binary heap data structure in order to store its task.

Constructors: 

  • Timer(): Creates a new timer
  • Timer(boolean isDaemon): Creates a new timer whose associated thread may be specified to run as a daemon
  • Timer(String name): Creates a new timer whose associated thread has the specified name
  • Timer(String name, boolean isDaemon): Creates a new timer whose associated thread has the specified name, and may be specified to run as a daemon

Declaration:  

public class Timer         extends Object

Methods inherited from class java.lang.Object

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

Methods: 

  • cancel(): java.util.Timer.cancel() Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it 
    Syntax: 
public void cancel()
  • purge(): java.util.Timer.purge() Removes all cancelled tasks from this timer’s task queue 
    Syntax: 
public int purge() Returns: the number of tasks removed from the queue
  • schedule(TimerTask task, Date time): java.util.Timer.schedule(TimerTask task, Date time) Schedules the specified task for execution at the specified time 
    Syntax: 
public void schedule(TimerTask task, Date time) Parameters: task - task to be scheduled. time - time at which task is to be executed. Throws: IllegalArgumentException - if time.getTime() is negative. IllegalStateException - if the task was already scheduled or cancelled,  the timer was cancelled, or timer thread terminated. NullPointerException - if task or time is null
  • schedule(TimerTask task, Date firstTime, long period): java.util.Timer.schedule(TimerTask task, Date firstTime, long period) Schedules the specified task for repeated fixed-delay execution, beginning at the specified time 
    Syntax: 
public void schedule(TimerTask task, Date firstTime, long period) Parameters: task - task to be scheduled. firstTime - First time at which task is to be executed. period - time in milliseconds between successive task executions. Throws: IllegalArgumentException - if firstTime.getTime() < 0,  or period <= 0 IllegalStateException - if task was already scheduled  or cancelled, timer was cancelled,  or timer thread terminated. NullPointerException - if task or firstTime is null

Java




// Java program to demonstrate
//schedule method calls of Timer 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);
    }
}
 
public class Test
{
    public static void main(String[] args)
    {
         
        Timer timer = new Timer();
        TimerTask task = new Helper();
         
        timer.schedule(task, 2000, 5000);
         
    }
}
 
 

Output: 

Timer ran 1 Timer ran 2 Timer ran 3 Timer ran 4 Timer ran 5 . . .
  • schedule(TimerTask task, long delay): java.util.Timer.schedule(TimerTask task, long delay) Schedules the specified task for execution after the specified delay 
    Syntax: 
public void schedule(TimerTask task, long delay) Parameters: task - task to be scheduled. delay - delay in milliseconds before task is to be executed. Throws: IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative. IllegalStateException - if a task was already scheduled  or cancelled, the timer was cancelled,  or timer thread terminated. NullPointerException - if task is null
  • schedule(TimerTask task, long delay, long period): java.util.Timer.schedule(TimerTask task, long delay, long period) Schedules the specified task for repeated fixed-delay execution, beginning after the specified delaySyntax: 
     
public void schedule(TimerTask task, long delay, long period) Parameters: task - task to be scheduled. delay - delay in milliseconds before task is to be executed. period - time in milliseconds between successive task executions. Throws: IllegalArgumentException - if delay < 0,  or delay + System.currentTimeMillis() < 0, or  period <= 0 IllegalStateException - if task was already scheduled  or cancelled, timer was cancelled,  or timer thread terminated. NullPointerException - if task is null
  • scheduleAtFixedRate(TimerTask task, Date firstTime, long period): java.util.Timer.scheduleAtFixedRate(TimerTask task, Date firstTime, long period) Schedules the specified task for repeated fixed-rate execution, beginning at the specified timeSyntax: 
     
public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) Parameters: task - task to be scheduled. firstTime - First time at which task is to be executed. period - time in milliseconds between successive task executions. Throws: IllegalArgumentException - if firstTime.getTime() < 0 or period <= 0 IllegalStateException - if task was already scheduled  or cancelled, timer was cancelled,  or timer thread terminated. NullPointerException - if task or firstTime is null
  • scheduleAtFixedRate(TimerTask task, long delay, long period): java.util.Timer.scheduleAtFixedRate(TimerTask task, long delay, long period) Schedules the specified task for repeated fixed-rate execution, beginning after the specified delaySyntax: 
     
public void scheduleAtFixedRate(TimerTask task, long delay, long period) Parameters: task - task to be scheduled. delay - delay in milliseconds before task is to be executed. period - time in milliseconds between successive task executions. Throws: IllegalArgumentException - if delay < 0,  or delay + System.currentTimeMillis() < 0, or  period <= 0 IllegalStateException - if task was already  scheduled or cancelled, timer was cancelled,  or timer thread terminated. NullPointerException - if task is null

Java




// Java program to demonstrate
// scheduleAtFixedRate method of Timer class
 
import java.util.Timer;
import java.util.TimerTask;
import java.util.*;
 
 
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
{
    protected static Test obj;
    public static void main(String[] args) throws InterruptedException
    {
        obj = new Test();
         
        //creating a new instance of timer class
        Timer timer = new Timer();
        TimerTask task = new Helper();
 
        //instance of date object for fixed-rate execution
        Date date = new Date();
 
        timer.scheduleAtFixedRate(task, date, 5000);
         
        System.out.println("Timer running");
        synchronized(obj)
        {
            //make the main thread wait
            obj.wait();
             
            //once timer has scheduled the task 4 times,
            //main thread resumes
            //and terminates the timer
            timer.cancel();
             
            //purge is used to remove all cancelled
            //tasks from the timer'stack queue
            System.out.println(timer.purge());
        }
    }
}
 
 

Output: 

Timer running Timer ran 1 Timer ran 2 Timer ran 3 Timer ran 4 0

Reference:  

  • Oracle



Next Article
java.time.Period Class in Java

M

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

Similar Reads

  • Java.util.TimerTask class in Java
    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
    3 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.Year Class in Java
    The java.time.Year class represents a year in the ISO-8601 calendar system, such as 2021. Year is an immutable date-time object that represents a year. This class does not store or represent a month, day, time, or time-zone. The years represented by this class follow the proleptic numbering system t
    8 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.time.YearMonth Class in Java
    Java YearMonth class provides the output of the format "year-month". This class is an immutable class which means that it defines objects which, once created, never change their value. Any field which will be derived from a year and month, like quarter-of-year, are often obtained. This class does no
    4 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.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.ZonedDateTime Class in Java
    ZonedDateTime is an immutable object representing a date-time along with the time zone. This class stores all date and time fields.This class stores time to a precision of nanoseconds and a time-zone, with a zone Offset used to handle local date-times. For example, the value “2nd October 2011 at 14:
    8 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