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

更新時間: 2020 年 6 月 26 日

6K+ 瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.