1

I have a java Timer and I want it to do something every time it ticks. For example, I want my program to output this:

Output that I want:

Tick 1 seconds passed
Tick 2 seconds passed
Tick 3 seconds passed
Tick 4 seconds passed
Tick 5 seconds passed
Time up, running do_something()...

What I have so far is this:

Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        System.out.println("Time up, running do_something()");
        do_something();
    }
};
timer.schedule(timerTask, 5);

Actual Output of my code so far is this:

Time up, running do_something()...

5 Seconds have passed when I reach this line.

8
  • You'll need a loop in there Sep 18, 2017 at 1:26
  • How exactly should I make the loop? Sep 18, 2017 at 1:27
  • 3
    Well, your Timer is setup for a milliseconds delay, so you're only going to get one time, you're going to have to use schedule(TimerTask, long, long) if you want it to repeat. You could also use two Timers, one repeating, one non-repeating set with different intervals. If you want one Timer, then you will need to determine when it was first activated, calculate the time between executions and make a determination about what to do. Once you've passed your threshold (i.e. 5 seconds), cancel the timer and do something else Sep 18, 2017 at 1:29
  • 1
    @cricket_007 If used correctly, a Timer is a (kind of) loop Sep 18, 2017 at 1:29
  • 1
    For example. stackoverflow.com/questions/32110208/… Sep 18, 2017 at 1:41

1 Answer 1

2

Well if your intentions are to loop, you should use the overloaded method of the schedule over Timer as:

timer.schedule(TimerTask task, long delay, long period);

which would schedule the specified task for repeated fixed-delay execution, beginning after the specified delay.

Not the answer you're looking for? Browse other questions tagged or ask your own question.