- Trending Categories
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
Cancel the Timer Task in Java
In order to cancel the Timer Task in Java, we use the java.util.TimerTask.cancel() method. The cancel() method returns a boolean value, either true or false. The cancel() method is used to cancel the timer task.
Declaration −The java.util.TimerTask.cancel() method is declared as follows −
public boolean cancel()
The cancel() methods returns true when the task is scheduled for one-time execution and has not executed until now and returns false when the task was scheduled for one-time execution and has been executed already.
Let us see a program to illustrate the use of the java.util.TimerTask.cancel() method −
Example
import java.util.*; class MyTask extends TimerTask { public void run() { System.out.println("Task is running"); } } public class Example { public static void main(String[] args) { Timer timer = new Timer(); // creating timer TimerTask task = new MyTask(); // creating timer task // scheduling the task at the specified time at fixed-rate timer.scheduleAtFixedRate(task,new Date(),2000); // cancelling the task and displaying its status System.out.println("Task is cancelled:"+task.cancel()); } }
Output
Task is running Task is cancelled:true
- Related Articles
- Call the run() method of the Timer Task in Java
- Remove all cancelled tasks from the timer's task queue in Java
- Terminate the timer in Java
- Timer Class in Java
- Schedule a task for execution in Java
- How can we implement a timer thread in Java?
- How to start the specific task of the task scheduler using PowerShell?
- Schedule a task for repeated fixed delay execution in Java
- Timer in C#
- Java Program to get the current value of the system timer in nanoseconds
- How to cancel XMLHttpRequest in AJAX?
- Schedule a task for execution in Java after a given delay
- Timer objects in Python
- Timer Interrupts in Arduino
- Timer registers in Arduino

Advertisements