Search code examples
javaseleniumappium

set timers / wait for nothing


My scenario is that from my app I open the waze wait 25sec, go to home screen, wait 10sec, than the system move back to waze, than I wait 15sec than again going to home page and wait there 10sec,

mainScreen.openWaze();
TimeWatch watch = TimeWatch.start();
double passedTimeInSeconds = 0;
System.out.println("start");
while (passedTimeInSeconds < 26.0) {
    passedTimeInSeconds = watch.time(TimeUnit.SECONDS);
    System.out.println("the seconds of 1 " + passedTimeInSeconds);
    wazeInApp.validateWhereToField();
}
watch.reset();
passedTimeInSeconds = 0;
wazeInApp.goToHomeScreen();
while (passedTimeInSeconds < 11.0) {
    passedTimeInSeconds = watch.time(TimeUnit.SECONDS);
    System.out.println("the seconds of 2 " + passedTimeInSeconds);
    wazeInApp.validateWhereToField();
}
watch.reset();
passedTimeInSeconds = 0;
while (passedTimeInSeconds < 16.0) {
    passedTimeInSeconds = watch.time(TimeUnit.SECONDS);
    System.out.println("the seconds 3 " + passedTimeInSeconds);
    wazeInApp.validateWhereToField();
}
wazeInApp.goToHomeScreen();

my console prints :

start
the seconds of 1 0.0
the seconds of 1 12.0
the seconds of 1 13.0
the seconds of 1 13.0
the seconds of 1 34.0
the seconds of 2 0.0
the seconds of 2 0.0
the seconds of 2 0.0
the seconds of 2 0.0
the seconds of 2 9.0
the seconds of 2 15.0
the seconds 3 0.0
the seconds 3 2.0
the seconds 3 4.0
the seconds 3 6.0
the seconds 3 9.0
the seconds 3 11.0
the seconds 3 13.0
the seconds 3 34.0

it looks strange that the prints are not at the correct time, also it beyond the time limits , and also does these is the right solution for just wait (for nothing)? Thank you


Solution

  • I believe you are trying to check for something in this 26 seconds times so you are not preferring Thread.sleep() I tried the below way and it worked for me. Here I am taking system current second and adding 26 to it(our expected time) so the loop will iterate till 26 seconds from current second.

    long passedTimeInSeconds = 0, earlierSecond = 0, currentSecond = 0;
    long waitTillTime =  Instant.now().getEpochSecond() +26;
    while(passedTimeInSeconds < waitTillTime){
        passedTimeInSeconds = Instant.now().getEpochSecond();
        earlierSecond = passedTimeInSeconds%60+1;
        currentSecond = Instant.now().getEpochSecond()% 60 + 1;
        if(currentSecond > earlierSecond) {
        System.out.println("Second: "+earlierSecond);
        }
     
    

    Output:

    Second: 37
    Second: 38
    Second: 41
    Second: 43
    Second: 44
    Second: 45
    Second: 46
    Second: 47
    Second: 49
    Second: 51
    Second: 52
    Second: 54
    Second: 58
    Second: 59
    Second: 1
    

    Due to milliseconds sometimes condition may fail.