Reputation: 4685
I have a code
for (int i = 0; i < 10000 i++) {
//call every 1000ms
Thread.sleep(1000);
doLongTimeOperation();
}
and long time operation
void doLongTimeOperation(){
//Long time op
Thread.sleep(randomInt);
}
I need to call this method every fixed period of time (1000). IE, if method executes in 500ms, next call should be after 500ms (500+500=1000). If method executes in 2000ms, next call should be after 0ms. How to implement it? Thanks
Upvotes: 0
Views: 278
Reputation: 6306
I believe what you actually want is schedule at fixed rate.
Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on.
Upvotes: 1
Reputation: 616
Best option is ScheduledExecutorService.scheduleWithFixedDelay method.
scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit):
"Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next."
For further details check this link:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleWithFixedDelay(java.lang.Runnable, long, long, java.util.concurrent.TimeUnit)
No tension of calculating anything :). Note its different than scheduleAtFixedRate method. Hope it helps.
Upvotes: 1
Reputation: 6410
The simple answer to your question is measure how long it took using System.currentTimeMillis () before and after to measure the difference. Subtract that difference from your desired wait time.
long start = System.сurrentTimeMillis();
// do stuff
long duration = System.сurrentTimeMillis()-start;
Thread.sleep (1000-duration);
Upvotes: -1