![](/img/trans.png)
[英]How to call a function in java if the program doesn't return anything after n seconds
[英]Java Timer to call function n times after every t seconds
我希望Java Timer每t秒后調用n次函數。 我現在正在嘗試此操作,它每隔t秒就會調用一次函數,但是我希望此函數僅被調用n次。
Timer tt = new Timer();
tt.schedule(new MyTimer(url), t);
我認為Timer
沒有內置功能。 您將需要添加一個計數器來為每個調用計數,然后在n次之后使用cancel()
停止計時器。
像這樣:
final int[] counter = {n};
final Timer tt = new Timer();
tt.schedule(new TimerTask(){
public void run() {
//your job
counter[0]--;
if (counter[0] == 0) {
tt.cancel();
}
}
}, t);
嘗試執行器服務。 您必須自己計算一次,多久調用一次Callable並取消Timer。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.