Thursday, May 7, 2026
HomeLanguagesJavaTimer cancel() method in Java with Examples

Timer cancel() method in Java with Examples

The cancel() method of Timer class is used to terminate this timer and remove any currently scheduled tasks.

Syntax:

public void cancel()

Parameters: The function does not accepts any parameter.

Return Value: The method has no return value.

Exception: The function does not throws any exception.

Program below demonstrates the above mentioned function:

Program 1:




// program to demonstrate the
// function java.util.Timer.cancel()
  
import java.util.*;
public class GFG {
    public static void main(String[] args)
    {
  
        // creating timertask, timer
        Timer timer = new Timer();
        TimerTask tt = new TimerTask() {
  
            public void run()
            {
                for (int i = 1; i <= 15; i++) {
                    System.out.println("working on the task");
                    if (i >= 7) {
                        System.out.println("stop the task");
                        // loop stops after 7 iterations
                        timer.cancel();
                        break;
                    }
                }
            };
        };
        timer.schedule(tt, 1000, 1000);
    }
}


Output:

working on the task
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

Program 2:




// program to demonstrate the
// function java.util.Timer.cancel()
  
import java.util.*;
public class GFG {
    public static void main(String[] args)
    {
  
        // creating timertask, timer
        Timer timer = new Timer();
        TimerTask tt = new TimerTask() {
  
            public void run()
            {
                for (int i = 1; i <= 15; i++) {
                    System.out.println("working on the task");
                    if (i >= 7) {
                        System.out.println("stop the task");
                        // loop stops after 7 iterations
                        timer.cancel();
                    }
                }
            };
        };
        timer.schedule(tt, 1000, 1000);
    }
}


Output:

working on the task
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
working on the task
stop the task
working on the task
stop the task
working on the task
stop the task
working on the task
stop the task
working on the task
stop the task
working on the task
stop the task
working on the task
stop the task
working on the task
stop the task
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6891 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12105 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6962 POSTS0 COMMENTS