drkvader
drkvader

Reputation: 163

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

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

Upvotes: 1

Views: 2804

Answers (1)

Shubham Jain
Shubham Jain

Reputation: 17553

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){

Upvotes: 2

Related Questions