本文介绍了Java计时器在每t秒后调用函数n次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望 Java Timer 在每 t 秒后调用函数 n 次.我现在正在尝试这个它每隔 t 秒调用一次函数,但我希望这个函数只被调用 n 次.
I want Java Timer to call function n times after every t seconds. I am trying this right now it calls function after every t seconds but I want this function to be called for only n times.
Timer tt = new Timer();
tt.schedule(new MyTimer(url), t);
推荐答案
我认为 Timer
没有将其作为内置函数.您需要添加一个计数器来为每次调用计数,然后在 n 次后使用 cancel()
停止计时器.
I think Timer
doesn't have it as a built-in function. You will need to add a counter to count it for each call and then stop the timer using cancel()
after n times.
像这样:
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);
这篇关于Java计时器在每t秒后调用函数n次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!