是否有更简洁的方法来编写此轮询循环?

时间:2012-11-02 15:16:15

标签: java loops webdriver polling selenium-webdriver

我正在用Java编写Selenium / WebDriver中的自动化测试用例。我实现了以下代码来轮询现有的WebElements,但由于我不是Java的专家,我想知道是否有更简洁的方法来编写此方法:

/** 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");
        }
    }

这条特殊的界限让我觉得代码有点脏:

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

2 个答案:

答案 0 :(得分:2)

你可以做这样的事情

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

答案 1 :(得分:0)

如何以毫秒使用系统时间?

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) {
  }
}
相关问题