2009-09-11 20 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

+0

が、それは両方を持っていることをお勧めだ@Jackyそれが良い(EffetiveのJavaブック)によると、最終的に –

+0

をtimer.cancel()を追加することである持っている必要はありません、キャンセルは十分にあると思いますが、理論的には 'cancel'自体が動作します。 –

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 

お知らせ進行中のtimertaskを終了しない。

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); 
関連する問題