Java TimerTask - cancel() Method
The java.util.TimerTask.cancel() method is used to cancel this timer task. If the task has been scheduled for one-time execution and has not yet run, or has not yet been scheduled, it will never run. If the task has been scheduled for repeated execution, it will never run again. (If the task is running when this call occurs, the task will run to completion, but will never run again.)
Syntax
public boolean cancel()
Parameters
No parameter is required.
Return Value
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. (Returns true if it prevents one or more scheduled executions from taking place.)
Exception
NA.
Example:
In the example below, the java.util.TimerTask.cancel() method is used to cancel the given timer task.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a timer Timer timer = new Timer(); //creating a timertask TimerTask tt = new TimerTask() { public void run() { System.out.println("Working on the task."); }; }; //scheduling the task to be executed //immediately and after that execute //the task at period of 1000 milliseconds timer.schedule(tt, 0, 1000); //cancelling the task System.out.println("Cancelling the task: " + tt.cancel()); } }
The output of the above code will be:
Cancelling the task: true
❮ Java.util - TimerTask