Monday, January 5, 2015

Java: Example of Wait Method in Java

Following is an example to implement Wait Method for predefined seconds in Java. Useful in Selenium, when you don't have control to wait for some element to load in Rich-faces, etc.

 package selenium;  
 import java.util.concurrent.TimeUnit;  
 import org.apache.log4j.Logger;  
 public class WaitMethod  
 {  
   protected void waitForAFewSecond(int timeS)  
   {  
     try  
     {  
       long timeInMS, timeInSec, timeOutMS, timeOutSec;  
       timeInMS = System.currentTimeMillis();  
       timeInSec = TimeUnit.MILLISECONDS.toSeconds(timeInMS);  
       do  
       {  
         timeOutMS = System.currentTimeMillis();  
         timeOutSec = TimeUnit.MILLISECONDS.toSeconds(timeOutMS);  
       }  
       while (timeOutSec - timeInSec < timeS);  
     }  
     catch (Exception e)  
     {  
       System.out.println(e.getMessage());  
     }  
   }  
 }