2009-09-11 56 views

回答

94

保持到定时参考的地方,并使用:

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 .... 

} 
+4

我想取消就足够了,并不需要有净化 – Jacky 2015-05-30 08:43:40

+0

是好到最后根据(Effetive的Java书)添加timer.cancel() – 2015-07-02 05:04:49

+0

@Jacky这是很好的做法兼得,但理论上'取消'本身就可以工作。 – 2016-04-28 00:03:59

13

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

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 

注意,只是取消将计时器不终止正在进行的时间任务。

9
timer.cancel(); //Terminates this timer,discarding any currently scheduled tasks. 

timer.purge(); // Removes all cancelled tasks from this timer's task queue. 
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);