1

I try to achieve a timer with several loops as below

while ( $try < 3) {
    eval {
        local $SIG{ALRM} = {};
        alarm 3;
        $ret = # sending request and wait for response
        alarm 0;
    }
    last if defined($ret);
    $try++;
}

But actually, when the alarm expired, the whole 'while' loop got interrupted, and the loop didn't happen at all.

Where I got the thing wrong?

1 Answer 1

1

You need to set an ALRM Handler, just like the alarm docs demonstrate:

for (1..3) {    
    print "Loop $_\n";

    eval {
        local $SIG{ALRM} = sub { die "alarm\n" };
        alarm 5;

        my $count = int rand 10;
        print "Is $count < 5?\n"; 
        sleep $count;

        alarm 0; #cancel the alarm if does not hang
    };

    if ($@) {
        die unless $@ eq "alarm\n";   # propagate unexpected errors
    } else {
        print "Our code succeeded\n";
        last;
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I wrote a handler at first time, but looked not working either. I'll try it again.
What I've demonstrated should work just fine. Can even just copy/paste this into a script to confirm before trying to integrate it into your code.
Yes, thanks. I used "timeout\n" instead of "alarm\n". After I changed to "alarm\n", everything is working. Thanks. So for my dumb, "alarm\n" looks quite fixed.
En, not exactly the case about 'alarm\n'. I found '$@' is not certain in my case, so when I tried to check the output of the exception, it always dies. I guess in my context (some super class or something else) throw some output at the same time to make '$@' not certain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.