Ahmed Masud
Ahmed Masud

Reputation: 612

Java Timer to call function n times after every t seconds

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

Upvotes: 0

Views: 4744

Answers (2)

evanwong
evanwong

Reputation: 5134

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

Upvotes: 4

Christian Kuetbach
Christian Kuetbach

Reputation: 16060

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

Upvotes: 0

Related Questions