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 secondsb // after 5 secondsc // after 10 seconds