0

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);
Ahmed Masud
  • 614
  • 1
  • 10
  • 24

2 Answers2

4

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);
evanwong
  • 5,054
  • 3
  • 31
  • 44
  • You are decrementing `n` and then checking `counter`? How do you suppose this will work? You need `final int[] counter = {n}` and then `counter[0]--` and then `if (counter[0] == 0)`. It is also better to have `Timer` as a long-running object and submit new `TimerTask`s to it (and cancel the `TimerTask`s). – Marko Topolnik May 14 '12 at 20:25
  • Decrementing `n` was a typo. Thanks for pointing that out and fixed now. Regarding the `Timer` or `TimerTask` should be canceled, I think that depends on the program requirement. If the program should exist right after n jobs, then the `Timer` should be canceled. If the program will be running continuously and `Timer` will be reused, you are totally right that the `TimerTask` should be canceled. Why counter should be an array tho? – evanwong May 14 '12 at 20:40
  • 2
    Did you try compiling that code? Now you are trying to decrement a final var. You can't close over non-final local var so I showed you the standard trick to get around that. – Marko Topolnik May 14 '12 at 20:56
  • I didn't really code it. I was just trying to show an idea. You are correct about the final var decrement and I just fixed in the example above. +1 for your comment. Thanks. – evanwong May 14 '12 at 21:07
  • +1 for fixing the example :) It is after all a much more useful answer when it's correct and shows all the tricks involved. – Marko Topolnik May 14 '12 at 21:16
0

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

Christian Kuetbach
  • 15,850
  • 5
  • 43
  • 79