Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 972
squeemish Avatar asked Apr 06 '26 05:04

squeemish


1 Answers

You can do something like this

long t = System.currentMillis();   // actual time in milliseconds from Jan 1st 1970.
while (t > System.currentMillis() - 30000 )  {
   ...
like image 199
Chuidiang Avatar answered Apr 09 '26 10:04

Chuidiang