Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I limit the time spent in a specific section of a Perl script?

Tags:

timeout

perl

Is there any way to build some time counter that enable parts of a script to run as long it ticks? For example, I have the following code:

for my $i (0 .. $QUOTA-1) {
    build_dyna_file($i);
    comp_simu_exe;
    bin2txt2errormap($i);
}

Theoretically I want to run this loop for 3 minutes, even if the loop instructions haven't finished yet, it should still break out of the loop after exactly 3 minutes.

Actually the program opens a time counter window that works in parallel to part of the script (each time I call it).

Additionally, the sub call 'comp_simu_exe' run an outside simulator (in the shell) that when time out ends - this process must also killed (not suppose to return after a while).

sub comp_simu_exe{

system("simulator --shell");
}

Is there any connection between the dead coming problem to the system function call ?

like image 250
YoDar Avatar asked Jul 22 '09 13:07

YoDar


1 Answers

You can set an alarm that will break out of your code after a specified amount of seconds:

eval {
    local $SIG{ ALRM } = sub { die "TIMEOUT" };
    alarm 3 * 60;
    for (my $i = 0 ; $i <$QUOTA ; $i++) {
        build_dyna_file($i);
        comp_simu_exe;
        bin2txt2errormap($i);
    }
    alarm 0;
};

if ( $@ && $@ =~ m/TIMEOUT/ ) {
    warn "operation timed out";
}
else {
    # somebody else died
    alarm 0;
    die $@;
}

Or, if you really need the loop to run at least three times, no matter how long this might take:

eval {
    my $t0 = time;
    local $SIG{ ALRM } = sub { die "TIMEOUT" };

    for (my $i = 0 ; $i <$QUOTA ; $i++) {
        build_dyna_file($i);
        comp_simu_exe;
        bin2txt2errormap($i);
        if ( $i == 3 ) {
            my $time_remaining = 3 * 60 - time - $t0;
            alarm $time_remaining if $time_remaining > 0;
        }
    }
    alarm 0;
};
like image 127
innaM Avatar answered Sep 28 '22 02:09

innaM