【问题标题】:How to stop the task scheduled in java.util.Timer class如何停止在 java.util.Timer 类中安排的任务
【发布时间】:2010-11-27 09:41:39
【问题描述】:

我正在使用java.util.Timer 类,我正在使用它的 schedule 方法来执行一些任务,但是在执行了 6 次之后我不得不停止它的任务。

我该怎么做?

【问题讨论】:

  • 更新:TimerTimerTask 类已被取代,如其 Javadoc 中所述。学习使用添加到 Java 5+ 的 Executors 框架。请参阅 Oracle 的 Java Tutorials

标签: java timer


【解决方案1】:

在特定时间唤醒后终止定时器一次(以毫秒为单位)。

Timer t = new Timer();
t.schedule(new TimerTask() {
            @Override
             public void run() {
             System.out.println(" Run spcific task at given time.");
             t.cancel();
             }
 }, 10000);

【讨论】:

    【解决方案2】:
    timer.cancel();  //Terminates this timer,discarding any currently scheduled tasks.
    
    timer.purge();   // Removes all cancelled tasks from this timer's task queue.
    

    【讨论】:

      【解决方案3】:

      您应该停止在计时器上安排的任务: 你的计时器:

      Timer t = new Timer();
      TimerTask tt = new TimerTask() {
          @Override
          public void run() {
              //do something
          };
      }
      t.schedule(tt,1000,1000);
      

      为了停止:

      tt.cancel();
      t.cancel(); //In order to gracefully terminate the timer thread
      

      请注意,仅取消计时器不会终止正在进行的计时器任务。

      【讨论】:

      • 我有两种方法。是否可以从不同的方法停止 TimerTask?
      【解决方案4】:

      在某处保留对计时器的引用,并使用:

      timer.cancel();
      timer.purge();
      

      停止它正在做的任何事情。您可以将此代码放在您正在执行的任务中,并使用static int 来计算您已经完成的次数,例如

      private static int count = 0;
      public static void run() {
           count++;
           if (count >= 6) {
               timer.cancel();
               timer.purge();
               return;
           }
      
           ... perform task here ....
      
      }
      

      【讨论】:

      • 我觉得cancel就够了,不需要purge
      • 根据(Effetive Java book)在final中添加timer.cancel()好不好
      • @Jacky 两者兼有是个好习惯,但理论上 cancel 本身也可以。
      • @Jacky 是对的。看Timer的实现。取消后调用 purge 绝对没用。 Cancel 清除整个任务列表,而 purge 遍历同一列表,检查状态是否为 CANCELED,然后删除任务。
      • 如果启动Timer的activity/fragment被销毁或停止,Timer预定的会自行停止吗?
      【解决方案5】:

      如果这就是它所做的全部,请致电cancel() on the Timer,或者如果计时器本身还有其他您希望继续的任务,请致电cancel() on the TimerTask

      【讨论】:

        猜你喜欢
        • 2011-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-20
        • 1970-01-01
        • 2012-05-02
        相关资源
        最近更新 更多