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.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
WhatsYourIdea
  • 351
  • 2
  • 12
  • You'll need a loop in there – OneCricketeer Sep 18 '17 at 01:26
  • How exactly should I make the loop? – WhatsYourIdea Sep 18 '17 at 01: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 `Timer`s, 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 – MadProgrammer Sep 18 '17 at 01:29
  • 1
    @cricket_007 If used correctly, a `Timer` is a (kind of) loop – MadProgrammer Sep 18 '17 at 01:29
  • @Mad Yes, using the other schedule methods. – OneCricketeer Sep 18 '17 at 01:31
  • I guess I didn't say it clearly at the beginning. I am trying to notify the user about the progress of the timer. So, I need to print the status of the timer every time the timer TICKS. For example, if the Timer ticks from 1000 ms left to 999 ms left, I want to print out the remaining time, like so: "999ms left" – WhatsYourIdea Sep 18 '17 at 01:36
  • You can extend the TimerTask to add a field that counts up/down, then. The functional differences between schedule methods are still the same – OneCricketeer Sep 18 '17 at 01:39
  • 1
    For example. https://stackoverflow.com/questions/32110208/creating-a-count-down-timer-java – OneCricketeer Sep 18 '17 at 01:41

1 Answers1

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.

Naman
  • 27,789
  • 26
  • 218
  • 353