取消 Java 中的 Timer 任务
为了取消 Java 中的 Timer 任务,我们使用 java.util.TimerTask.cancel() 方法。cancel() 方法返回一个布尔值,为 true 或 false。cancel() 方法用于取消计时任务。
声明 − java.util.TimerTask.cancel() 方法声明如下 −
public boolean cancel()
cancel() 方法在任务被安排为单次执行并且至今尚未执行时返回 true,并且在任务被安排为单次执行并且已经执行时返回 false。
让我们查看一个程序来演示 java.util.TimerTask.cancel() 方法的使用 −
示例
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());
}
}输出
Task is running Task is cancelled:true
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP