Java Timer - cancel() Method
The java.util.Timer.cancel() method is used to terminate the given timer, discarding any currently scheduled tasks.
Syntax
public void cancel()
Parameters
No parameter is required.
Return Value
void type.
Exception
NA.
Example:
In the example below, the java.util.Timer.cancel() method is used to terminate the given timer.
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() { for (int i = 0; i <= 10; i++) { System.out.println("Working on the task."); if(i==5) { System.out.println("Stop the task."); timer.cancel(); break; } } }; }; //scheduling the task to be executed //after a delay of 100 milliseconds timer.schedule(tt, 100); } }
The output of the above code will be:
Working on the task. Working on the task. Working on the task. Working on the task. Working on the task. Working on the task. Stop the task.
❮ Java.util - Timer