- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Timer Class in Java
- Cancel the Timer Task in Java
- Call the run() method of the Timer Task in Java
- How can we implement a timer thread in Java?
- How to terminate/destroy a process using Process API in Java 9?
- Java Program to get the current value of the system timer in nanoseconds
- Timer in C#
- Remove all cancelled tasks from the timer's task queue in Java
- How to terminate javascript forEach()?
- Timer objects in Python
- Timer Interrupts in Arduino
- Timer registers in Arduino
- Watchdog timer in Arduino
- How do I terminate a thread in C++11?
- Timer in C++ using system calls

Advertisements