-3
A
回答
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
我現在沒有時間來測試這一權利,但這應該工作
這是一種方式:
- 你的方法,你想從這裏調用可能需要是靜態
- 這個類可以被嵌套在另一個類
- 可以使用%(模數),所以計時器可以保持計數,你可以設置在東西更多的時間間隔
創建此計時器:
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
}
}
}
相關問題
- 1. EnableRaisingEvents每100毫秒?
- 2. 如何使用增量毫秒來每x毫秒執行一次?
- 3. 每100毫秒暫停Exoplayer,500毫秒後重新開始
- 4. 毫秒到秒?
- 5. 格式時間從秒到毫秒:秒:毫秒:微秒
- 6. LookupAccountSid每次撥打+600毫秒
- 7. Android毫秒
- 8. MPMusicPlayerController currentPlaybackTime - 毫秒
- 9. 毫秒PHP
- 10. 毫秒的MySQL
- 11. 捕捉毫秒
- 12. wxDateTime ParseFormat()毫秒
- 13. 顯示毫秒
- 14. 毫微秒到毫微秒的轉換毫秒數<999999在Java中
- 15. 倒計時秒數:毫秒
- 16. 以秒,毫秒顯示datediff
- 17. 毫秒級的jQuery秒錶
- 18. 運行函數每2毫秒
- 19. 轉換納秒到毫秒不工作
- 20. 10毫秒C++執行時間
- 21. 如何在100毫秒內獲得自動完成響應(毫秒)
- 22. 每n毫秒寫一個字符串
- 23. 在毫秒QTTime工作
- 24. 將時間轉換爲秒+毫秒秒
- 25. SimpleDateFormat的 - 用毫秒
- 26. java.util.Date中取毫秒
- 27. 毫秒計時C++
- 28. TimeSpan到UTC毫秒
- 29. 比較datetime毫秒
- 30. 每x秒執行一次動作delphi
@Mike蓋茨和您的解決方案都是正確的。 我使用的是哪一種?因爲我在這裏選擇答案有點困難...... – tomi 2012-08-10 15:39:05
取決於你想做什麼,如果你想做任何UI工作(與視圖交互),你需要使用我的方法。如果它不是基於UI的@Mike Gates解決方案更清潔。 – Jug6ernaut 2012-08-10 16:59:26
thx澄清。 – tomi 2012-08-11 15:29:25