當我們想要延遲某段時間後再執行某程式碼、或是循環執行程式碼時,就可以使用Timer
過xxx ms後執行某程式碼:
long delay = 120;
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
//想要延遲執行的程式
timer.cancel();
}
},delay);
循環執行某些程式碼:
long period = 500;//循環間隔
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
//想要循環執行的程式
}
}, 0, period);
合併起來使用時:在xxx ms後循環執行
long delay = 120;//延遲執行
long period = 500;//循環間隔
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
//想要延遲循環執行的程式
}
}, delay, period);
-END-
發佈留言