Home > Net >  Using Java's Timer to wait for a period of time between loop iterations
Using Java's Timer to wait for a period of time between loop iterations

Time:08-01

Learning to use the Java Timer.

If I want to print the contents of an iterator inside a loop and wait for say 5 seconds inbetween each print, I could use Thread.sleep. But I'm trying to do this without Thread.sleep. This is my attempt so far:

        do {
            Timer printTimer = new Timer();
            printTimer.schedule(
                new TimerTask() {
                  @Override
                  public void run() {  
                    print(myIterator.next().toString()); // using System.out.println internally
                 }
                }, 5000);
        } while (myIterator.hasNext())

However, the above basically results in an infinite loop. It doesn't execute the task once per iteration and wait 5 seconds like I could do with Thread.sleep. In other words, it doesn't seem to check the myIterator.hasNext() condition.

Is there a way to get it to simulate a call to Thread.sleep(5000) after printing?

CodePudding user response:

The reason why it seems to be looping infinitely, is because the myIterator.next() call doesn't happen until the TimerTask is executed, so myIterator.hasNext() is not updating on each loop iteration. Try moving the myIterator.next() call outside of the TimerTask and inside the loop.

You can also maintain a count of each iteration to schedule each task in 5 second increments, as well as reusing the Timer instance.

I would also recommend using a while loop instead of a do-while loop, unless you're certain that your iterator will always have at least one element, or else you may get a NoSuchElementException.

Here is a working example:

List<String> list = Arrays.asList("a", "b", "c");
Iterator<String> iterator = list.iterator();
int i = 0;
Timer timer = new Timer();
while(iterator.hasNext()) {
    String value = iterator.next();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            System.out.println(value);
        }
    };
    timer.schedule(task, 5000L * i  );
}

Which outputs the following:

a // after 0 seconds
b // after 5 seconds
c // after 10 seconds
  • Related