23

How do I delay a while loop to 1 second intervals without slowing down the entire code / computer it's running on to the one second delay (just the one little loop).

AstroCB
  • 11,800
  • 20
  • 54
  • 68
Gray Adams
  • 3,147
  • 8
  • 26
  • 37
  • 1
    _without slowing down the entire code_ elaborate this – jmj Dec 21 '11 at 07:05
  • @JigarJoshi I'm trying to delay this while loop at 1 second intervals for my Minecraft plugin. But most of the wait methods pause the entire server for the set time, rather than just the loop – Gray Adams Dec 21 '11 at 07:08
  • you want the execution of while loop for a fixed period of time and then again in fixed delay. – Dead Programmer Dec 21 '11 at 07:08

4 Answers4

35

Thread.sleep(1000); // do nothing for 1000 miliseconds (1 second)

COD3BOY
  • 11,484
  • 1
  • 34
  • 55
12

It seems your loop runs on Main thread and if you do sleep on that thread it will pause the app (since there is only one thread which has been paused), to overcome this you can put this code in new Thread that runs parallely

try{

  Thread.sleep(1000);
}catch(InterruptedException ex){
  //do stuff
}
jmj
  • 225,392
  • 41
  • 383
  • 426
4

My simple ways to delay a loop.

I already put the codes here after failing to follow the stackoverflow's standards.

//1st way: Thread.sleep : Less efficient compared to 2nd
try {
  while (true) {//Or any Loops
   //Do Something
   Thread.sleep(sleeptime);//Sample: Thread.sleep(1000); 1 second sleep
  }
 } catch (InterruptedException ex) {
   //SomeFishCatching
 }
//================================== Thread.sleep


//2nd way: Object lock waiting = Most efficient due to Object level Sync.
Object obj = new Object();
 try {
  synchronized (obj) {
   while (true) {//Or any Loops
   //Do Something
   obj.wait(sleeptime);//Sample obj.wait(1000); 1 second sleep
   }
  }
 } catch (InterruptedException ex) {
   //SomeFishCatching
 }
//=============================== Object lock waiting

//3rd way:  Loop waiting = less efficient but most accurate than the two.
long expectedtime = System.currentTimeMillis();
while (true) {//Or any Loops
   while(System.currentTimeMillis() < expectedtime){
     //Empty Loop   
   }
   expectedtime += sleeptime;//Sample expectedtime += 1000; 1 second sleep
   //Do Something
}
//===================================== Loop waiting
D.R.Bendanillo
  • 261
  • 2
  • 7
  • 3
    I like the third way, because it can inhibit a whole cpu core and no one would _ever_ call this a code smell. – Tom Nov 05 '15 at 16:36
  • Another advantage of the third method is it does not require additional try/catch blocks. – Adam Howell Jul 12 '19 at 16:58
1

As Jigar has indicated you can use another Thread to do work which can operate, sleep etc independently of other Threads. The java.util.Timer class might help you as well since it can perform periodic tasks for you without you having to get into multithreaded programming.

Paul Jowett
  • 6,336
  • 2
  • 20
  • 18