Terminate the timer in Java

Java 8Object Oriented ProgrammingProgramming

One of the methods of the Timer class is the cancel() method. It is used to terminate the current timer and get rid of any presently scheduled tasks.

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

public void cancel()

Let us see a program which uses the cancel() method


 Live Demo

import java.util.*;
public class Example {
   Timer t;
   public Example(int seconds) {
      t = new Timer();
      t .schedule(new Running(), seconds);
   class Running extends TimerTask {
      public void run() {
         System.out.println("Task is cancelled");
         t.cancel(); // cancels the timer thread
   public static void main(String args[]) {
      new Example(8000); // setting a delay of 8000 milliseconds or 8 seconds
      System.out.println("Task is scheduled");

When the program is first executed, the immediate output is as follows

Task is scheduled

After a delay of 8 seconds, we see the following −

Task is cancelled

Thus, the final output after 8 seconds looks as follows −

Task is scheduled
Task is cancelled
Published on 07-Jan-2019 12:49:45