Cancel the Timer Task in Java


In order to cancel the Timer Task in Java, we use the java.util.TimerTask.cancel() method. The cancel() method returns a boolean value, either true or false. The cancel() method is used to cancel the timer task.

Declaration −The java.util.TimerTask.cancel() method is declared as follows −

public boolean cancel()

The cancel() methods returns true when the task is scheduled for one-time execution and has not executed until now and returns false when the task was scheduled for one-time execution and has been executed already.

Let us see a program to illustrate the use of the java.util.TimerTask.cancel() method −

Example

 Live Demo

import java.util.*;
class MyTask extends TimerTask {
   public void run() {
      System.out.println("Task is running");
   }
}
public class Example {
   public static void main(String[] args) {
      Timer timer = new Timer(); // creating timer
      TimerTask task = new MyTask(); // creating timer task
      // scheduling the task at the specified time at fixed-rate
      timer.scheduleAtFixedRate(task,new Date(),2000);
      // cancelling the task and displaying its status
      System.out.println("Task is cancelled:"+task.cancel());
   }
}

Output

Task is running
Task is cancelled:true

Updated on: 26-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements