Telling a Thread to Sleep

Introduction

In Java Applications it can be useful to put a Thread in a waiting mode for a certain period. This is possible with the sleep method of Thread. Since Threads can be interrupted, this method can throw an InterruptedException which should be caught. The example below shows how to do it.

try { long numMillisecondsTo = 600000; 
//10 minutes 
Thread.sleep(numMillisecondsTo); 
doSomething();
 } catch (InterruptedException e) {
}

The code above will run the method doSomething();

exactly 10 minutes after it was started.

Making something useful with this

When you want code to run scheduled (like every 10 minutes) you can wrap the code above in an endless loop like:

 

While (true){
   doSomething();
}

This will run the code in  doSomething(); continuously, without pauses.

To run it with an interval of exactly 10 minutes use the following:

While (true){
try { long numMillisecondsTo = 600000; 
//10 minutes 
Thread.sleep(numMillisecondsTo); 
 doSomething();
  } catch (InterruptedException e) {        
 }
}

This will execute the code in doSomething() exactly every 10 minutes. Adjust the value of numMillisecondsTo to the schedule you want.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.