ankit.tayal560 has asked for the wisdom of the Perl Monks concerning the following question:

use warnings; use strict; use Win32::GuiTest qw(:ALL); until(my @window3=FindWindowLike(undef,"calculator")) { print("\ncan't find window\n"); sleep 1; } print("Calculator is not opened\n");

I've written a piece of my code here which searches for a window title "Calculator" and prints a message can't find window till it does not find the required window.

I want to search for calculator window only for 30 seconds and if the search result is still negative after 30 seconds I want to come out of the until loop and print calculator is not opened.

How to run this section of code for 30 seconds?

Any suggestions or help is appreciated

Replies are listed 'Best First'.
Re: How to Run a section of code for a particular amount of time ?
by marto (Cardinal) on Nov 11, 2016 at 09:54 UTC

    Hello, again... we've discussed this module for some time now, I've suggested in the past that you read the documentation. The WaitWindowLike method sounds more suitable for your use case:

    WaitWindowLike($parent,$wndtitle,$wndclass,$wndid,$depth,$wait) Function which allows one to wait for a window to appear vs. using har +d waits (e.g. sleep 2). parent - Where to start (parent window) wndtitle - Regexp for the window title wndclass - Regexp for the window class name wndid - Numeric Window or Control ID depth - How deep should we search before we stop wait - How many seconds should we wait before giving up

    Note the last line. So once again, please take the time to read and understand the documentation for the tools you choose to use.

Re: How to Run a section of code for a particular amount of time ?
by GrandFather (Saint) on Nov 11, 2016 at 09:56 UTC

    The simplest way is just to use time. Something like:

    my $end = time + 30; while (time < $end) { ... }
    Premature optimization is the root of all job security
Re: How to Run a section of code for a particular amount of time ?
by choroba (Cardinal) on Nov 11, 2016 at 09:53 UTC
    Declare a variable $try_count and increment it inside the loop. Exit the loop if $try_count > 30 .

    BTW, the current code outputs "Calculator is not opened" even after opening it.

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
Re: How to Run a section of code for a particular amount of time ?
by Ratazong (Monsignor) on Nov 11, 2016 at 09:54 UTC

    Measure the time spent in the loop and create an additional exit condition. As the main time in your loop is spent sleeping for one second, you may as well count how often the loop has been executed, as shown below

    HTH, Rata

    my $count = 0; until((@window3=FindWindowLike(undef,"calculator")) || ($count > 29)) { print("\ncan't find window\n"); sleep 1; $count ++; }