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.
Timer
is setup for a milliseconds delay, so you're only going to get one time, you're going to have to useschedule(TimerTask, long, long)
if you want it to repeat. You could also use twoTimer
s, one repeating, one non-repeating set with different intervals. If you want oneTimer
, 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 elseTimer
is a (kind of) loop