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 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.
- TimerTask(): Creates a new timer task
public abstract class TimerTask
- cancel(): java.util.TimerTask.cancel() Cancels this timer task
public boolean cancel()
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
public abstract void run()
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
public long scheduledExecutionTime()
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
Java program to demonstrate usage of TimerTask class
System.out.println("Timer ran" + ++i);
Timer timer =
TimerTask task =
System.out.println("Cancel the timer task: " + task.cancel());
Timer ran 1
Timer ran 2
Timer ran 3
Timer ran 4
Cancel the timer task: true
This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.