-1

Quite simple question, however, I have trouble with this. I want to use sleep.thread to click on buttons in a random range of numbers, for example 30-50 seconds. This must be a sleep command. There is a loop that clicks on the elements and my attempt to do that(I found this in another answer, not working for me)

List<WebElement> textfields = driver.findElements(By.className("_84y62"));


    System.out.println("total buttons " + textfields.size());

        for (WebElement e : textfields) {
            e.click();

                Thread.sleep((long)(Math.random() * 11 + 10));
            }
serengeti
  • 117
  • 2
  • 15

2 Answers2

0

If I wanted to pause between 30-50 seconds I would implement as follows:

private void sleepRandomly() {
    try {
        Thread.sleep(getMillis());
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }
}

private static long getMillis() {
    return (long) (Math.random() * 20_000 + 30_000);
}

Remember sleep expects the length of time to sleep to be in milliseconds.

James
  • 1,095
  • 7
  • 20
  • Thank you for reliable answer, it is working great. Previous code was just clicking trough buttons without delay. – serengeti May 29 '17 at 21:13
-1

Thread.sleep() uses values in argument in milliseconds, so to wait 50 sec, you should call: Thread.sleep(50000). To generate values in selected range, you could use simple formula randomNum = minimum + (long)(Math.random() * maximum)

Tarik
  • 26
  • 3
  • The formula is off. `Math.random() * maximum` will give you a range of `maximum` instead of `maximum - minimum`. – shmosel May 29 '17 at 20:59
  • Please, check the code, before down voting. [link](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java) – Tarik May 29 '17 at 21:04
  • You're using a **question** as your source? Did you not see the problem *`randomNum` can be bigger than `maximum`*? I was not the downvoter btw. – shmosel May 29 '17 at 21:07
  • Thanks for helping, I've got answer already. I didn't downvote too. – serengeti May 29 '17 at 21:20