Java TimerTask.cancel()

Syntax

TimerTask.cancel() has the following syntax.

public boolean cancel()

Example

In the following code shows how to use TimerTask.cancel() method.


//  w w w  .ja  v  a 2s. c  o  m

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

class MyTimerTask extends TimerTask {
  public void run() {
    System.out.println("Timer task executed.");
  }
}
public class Main {
  public static void main(String[] args) {

     TimerTask task = new MyTimerTask();
     Timer timer = new Timer();
     
     // scheduling the task
     timer.scheduleAtFixedRate(task, new Date(), 1000);
     
     // cancelling the task
     System.out.println("cancelling task: "+task.cancel());
  }
  // this is the implementation method
  public void run() {
     System.out.println("Working");
  }
}

The code above generates the following result.