squeemish
squeemish

Reputation: 147

Is there a cleaner way to write this polling loop?

I am writing automated test cases in Selenium/WebDriver in java. I have the following code implemented to poll for existing WebElements, but as I am not an expert in Java I was wondering if there is a cleaner way to write this method:

/** selects Business index type from add split button */
    protected void selectBusinessLink() throws Exception
    {
        Calendar rightNow = Calendar.getInstance();
        Calendar stopPolling = rightNow;
        stopPolling.add(Calendar.SECOND, 30);
        WebElement businessLink = null;
        while (!Calendar.getInstance().after(stopPolling))
        {
            try
            {
                businessLink = findElementByLinkText("Business");
                businessLink.click();
                break;
            }
            catch (StaleElementReferenceException e)
            {
                Thread.sleep(100);
            }
            catch (NoSuchElementException e)
            {
                Thread.sleep(100);
            }
            catch (ElementNotVisibleException e)
            {
                Thread.sleep(100);
            }
        }
        if (businessLink == null)
        {
            throw new SystemException("Could not find Business Link");
        }
    }

This particular line is what makes me think the code is a little dirty:

 while (!Calendar.getInstance().after(stopPolling))

Upvotes: 3

Views: 3601

Answers (2)

Andy
Andy

Reputation: 5218

How about using the System time in millis?

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 30);
long stopPollingTime = calendar.getTimeInMillis();
while (System.currentTimeMillis() < stopPollingTime) {
  System.out.println("Polling");
  try {
    Thread.sleep(100);
  } catch (InterruptedException e) {
  }
}

Upvotes: 0

Chuidiang
Chuidiang

Reputation: 1055

You can do something like this

long t = System.currentMillis();   // actual time in milliseconds from Jan 1st 1970.
while (t > System.currentMillis() - 30000 )  {
   ...

Upvotes: 2

Related Questions