我尝试使用以下几个循环实现一个计时器
while ( $try < 3) {
eval {
local $SIG{ALRM} = {};
alarm 3;
$ret = # sending request and wait for response
alarm 0;
}
last if defined($ret);
$try++;
}
但实际上,当警报到期时,整个'while'循环被中断,并且循环根本没有发生。
我弄错了什么?
答案 0 :(得分:1)
您需要设置ALARM处理程序,就像alarm
文档演示:
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;
}
}