Java Timer to call function n times after every t seconds

末鹿安然 提交于 2019-12-23 06:49:33

问题


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);

回答1:


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.

Something like this:

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);



回答2:


Try the Executor Service. You have to count youself, how often you called the Callable and cancel the Timer.



来源:https://stackoverflow.com/questions/10590222/java-timer-to-call-function-n-times-after-every-t-seconds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!