2009-09-11 59 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);