Java.util.TimerTask class in Java (original) (raw)

Last Updated : 26 Apr, 2022

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:

Declaration:

public abstract class TimerTask extends Object implements Runnable

Methods:

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.

public abstract void run() Description: The action to be performed by this timer task

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

Java program to demonstrate usage of TimerTask class

Java

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();

`` Timer timer = new Timer();

`` TimerTask task = new Helper();

`` timer.schedule(task, 1000 , 3000 );

`` System.out.println(task.scheduledExecutionTime());

`` synchronized (obj)

`` {

`` obj.wait();

`` }

`` System.out.println("Cancel the timer task: " + task.cancel());

`` timer.cancel();

`` }

}

Output:

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

Reference: