Would like to create a timer in Selenium and do some action until reach a defined period of time

无人久伴 提交于 2020-01-14 04:27:05

问题


I'm trying to keep executing an action in a loop until reach a specific period of time.

Example: execute something like sysout for 10 seconds, then stop the execution.

I have seen some information about Timer class but was not useful so far.

In the code below, trying the keep scrolling down (because it is a infinite scroll) the page until reach some time in seconds.

    JavascriptExecutor js = (JavascriptExecutor) driver;

    while(countdown <= 15) {
        //countdown should be my defined limit of time
        js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
    }

回答1:


Use below code:

import java.text.ParseException;
import java.util.concurrent.TimeUnit;


public class WaitAndExecute {

    public static void main(String[] args) throws InterruptedException, ParseException {

        long startTime = System.nanoTime();

        long endTime = startTime;
        long durationInSeconds = 0;
        long durationInNano = 0;
        while(durationInSeconds<10) {
            methodToTime();
            System.out.println("2 seconds");
            endTime = System.nanoTime();
            durationInNano = (endTime - startTime); // Total execution time in nano seconds
            durationInSeconds = TimeUnit.NANOSECONDS.toSeconds(durationInNano); // Total execution time in seconds

            if(durationInSeconds>=10) {
                System.out.println("10 seconds done");
                break;
            }

        }
        System.out.println(durationInSeconds);
    }

    private static void methodToTime() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

Output:

2 seconds 2 seconds 2 seconds 2 seconds 2 seconds 10 seconds done 10


Old code

Use below code :

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;

public class WaitAndExecute {

public static void main(String[] args) throws InterruptedException {
     int countdown = 1;
        while (countdown < 10){
            System.out.println(countdown);
            JavascriptExecutor js = (JavascriptExecutor) driver;  // pass your webdriver reference variable 
            js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
            ++countdown;
            TimeUnit.SECONDS.sleep(10);
        }

}

Change the below line number as per the iteration you need:

  while (countdown < 10){


来源:https://stackoverflow.com/questions/58181535/would-like-to-create-a-timer-in-selenium-and-do-some-action-until-reach-a-define

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!