- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Terminate the timer in Java
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
Example
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
Advertisements