2012-08-07 200 views

回答

1
Timer t = new Timer(); 
int count = 0; 
t.scheduleAtFixedRate(new TimerTask() { 
    count++; 
    // Do stuff 
    if (count >= 10) 
     t.cancel(); 
}, 0, 100); 

這安排了一個計時器來執行TimerTask,延遲0毫秒。它將每隔100毫秒執行一次TimerTask的正文。使用count來跟蹤您在任務中的位置,經過10次迭代後,您可以取消定時器。

作爲@ Jug6ernaut提到,確保您的任務不會花費很長時間來執行。冗長的任務(在你的情況下需要超過100毫秒的任務)會導致滯後/潛在的不良結果。

0

您可以通過使用Timer來完成此操作。

3
Handler h = new Handler(); 
int count = 0; 
int delay = 100;//milli seconds 
long now = 0; 

h.postDelayed(new Runnable(){ 

    public void run(){ 
     now = System.currentTimeMillis(); 
     //do something 

     if(10>count++) 
     h.postAtTime(this, now + delay); 
    }, 
delay}; 

請注意,您的操作必須考慮小於100毫秒來執行,否則將無法運行每100ms,這將是情況下的所有方法。

+0

@Mike蓋茨和您的解決方案都是正確的。 我使用的是哪一種?因爲我在這裏選擇答案有點困難...... – tomi 2012-08-10 15:39:05

+0

取決於你想做什麼,如果你想做任何UI工作(與視圖交互),你需要使用我的方法。如果它不是基於UI的@Mike Gates解決方案更清潔。 – Jug6ernaut 2012-08-10 16:59:26

+0

thx澄清。 – tomi 2012-08-11 15:29:25

0

我現在沒有時間來測試這一權利,但這應該工作

這是一種方式:

  • 你的方法,你想從這裏調用可能需要是靜態
  • 這個類可以被嵌套在另一個類
  • 可以使用%(模數),所以計時器可以保持計數,你可以設置在東西更多的時間間隔
發生

創建此計時器:

private Timer mTimer = new Timer(); 

啓動定時器:

mTimer.scheduleAtFixedRate(new MyTask(), 0, 100L); 

定時器類:

/** 
    * Nested timer to call the task 
    */ 
    private class MyTask extends TimerTask { 
     @Override 
     public void run() { 
      try { 
       counter++; 
       //call your method that you want to do every 100ms 
          if (counter == 10) { 
           counter = 0; 
           //call method you wanted every 1000ms 
          } 
       Thread.sleep(100); 
      } catch (Throwable t) { 
       //handle this - maybe by starting it back up again    
      } 
     }  
    }