取消 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