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() Âimportjava.util.*;publicclassGFG {    publicstaticvoidmain(String[] args)    { Â        // creating timertask, timer        Timer timer = newTimer();        TimerTask tt = newTimerTask() { Â            publicvoidrun()            {                for(inti = 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);    }} | 
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() Âimportjava.util.*;publicclassGFG {    publicstaticvoidmain(String[] args)    { Â        // creating timertask, timer        Timer timer = newTimer();        TimerTask tt = newTimerTask() { Â            publicvoidrun()            {                for(inti = 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);    }} | 
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


 
                                    







