Search code examples
javafor-looptimerbuffer

How to use a Timer to slow a for-loop down


In making a for loop, I would like to control how long it takes to 'refresh' the loop, and I figured I could do this with a timer.
My only problem is the Timer keeps running like a for loop - repeating and repeating and repeating - so it just keeps the for loop from repeating, which is not what I want.
My for loop code is here:

for(int i=0; i < 200; i += 4){
    System.out.println("Hopefully will only run once...per 5 secs");
    new java.util.Timer().schedule( 
        new java.util.TimerTask() {
            @Override
            public void run() {

            }
        }, 
        5000 // 5 sec buffer, but never stops buffering
    );
}

Solution

  • I think that you're looking for something like this:

    for(int i=0; i < 200; i += 4){
        System.out.println("Hopefully will only run once...per 5 secs");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    

    It's a nice, simple solution but the thread sleeps and doesn't do anything useful for most of the time. That's fine for most cases, but a more efficient solution would be to use a ScheduledExecutorService, which is like the Timer you tried, only more modern.

    Here's a rough sketch of how that might work:

    ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
    
    AtomicInteger i = new AtomicInteger(0);
    exec.scheduleAtFixedRate(() -> {
        int j = i.getAndAdd(4);
        if (j >= 200) {
            exec.shutdownNow();
            return;
        }
    
        System.out.println(j); //Will print 0,4,8 etc.. Once every 5 seconds
        //Do stuff
    }, 0, 5, TimeUnit.SECONDS);