简体   繁体   中英

Java TimerTask not canceling

My CheckStatus (TimerTask) is not stopping when I call cancel() inside the run method. this.cancel() also does not work. What am I doing wrong?

import java.util.TimerTask;
class CheckStatus extends TimerTask {
   int s = 3;
   public void run() {
      if (s > 0)
      {
         System.out.println("checking status");
         s--;
      }
      else
      {
         System.out.println("cancel");
         cancel();
      }
   }
}

Heres my driver

import java.util.*;
class Game {
   static Timer timer;
   static CheckStatus status;

   public static void main(String[] args) throws InterruptedException {        
      CheckStatus status = new CheckStatus();
      timer = new Timer();
      timer.scheduleAtFixedRate(status, 0, 3000);
   }  
}

It works for me - using exactly the code you posted, I saw:

checking status
checking status
checking status
cancel

... and nothing else, showing that the TimerTask has been cancelled - it's never executing again.

Were you expecting the Timer itself to shut down when it didn't have any more work to do? It doesn't do that automatically. It's not clear what your bigger goal is, but one option to avoid this is to make the TimerTask also cancel the Timer - that will work, but it's not terribly nice in terms of design, and means that the TimerTask can't run nicely within a timer which contains other tasks.

你正在调用计时器任务的取消方法,但你应该调用计时器本身的取消方法来获得你预期的行为。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM