“如何计数”;“可靠地”;perl中的300秒时间?
我怎样才能超时5分钟 我的程序是这样做的:“如何计数”;“可靠地”;perl中的300秒时间?,perl,time,Perl,Time,我怎样才能超时5分钟 我的程序是这样做的: # I need to try something every 3 seconds, for at most 5 minutes $maxtime = time() + (5 * 60); $success = 0; while (($success == 0) && (time() < $maxtime)) { $success = try_something(); sleep (3) if ($success == 0
# I need to try something every 3 seconds, for at most 5 minutes
$maxtime = time() + (5 * 60);
$success = 0;
while (($success == 0) && (time() < $maxtime)) {
$success = try_something();
sleep (3) if ($success == 0);
}
#我需要每3秒尝试一次,最多5分钟
$maxtime=time()+(5*60);
$success=0;
而($success==0)和&(time()<$maxtime)){
$success=尝试某事();
睡眠(3)如果($success==0);
}
问题是:这个程序在启动后运行。它运行的嵌入式系统没有rtc/时钟电池。时钟从2000年1月1日开始,然后在它运行的第一分钟,它进入网络,ntp将时钟设置为更新的时钟,使循环在5分钟超时之前退出
哪种方法是在perl脚本中“计算5分钟”的正确方法,即使系统时钟被其他外部程序更改?我认为在这里使用报警功能是有意义的
{
local $SIG{ALRM} = sub {
warn "Ooops! timed out, exiting";
exit(100); # give whatever exit code you want
};
## setup alaram
alarm( 5 * 60 );
my $success = 0;
until($success) {
$success = try_something()
or sleep 3;
}
## deactivate alarm if successful
alarm(0);
}
如果try_something()花费了不可忽略的时间,则可以循环100次。或者,如果系统很忙,您的睡眠时间通常超过3秒,use Time::HiRes'sleep'
并将sleep的返回值相加,直到达到300
如果不是,那么可能是这样的:
my $last_time = my $start_time = time();
while () {
try_something() and last;
my $time = time();
# system clock reset? (test some limit that is more than try_something could ever take)
if ( $time - $last_time > 86400 ) {
$start_time += $time - $last_time;
}
$last_time = $time;
sleep( List::Util::min( 3, $start_time + 300 - $time ) );
}
您想使用一个单调计时器;例如,
选择
和轮询
超时使用该选项
select undef, undef, undef, 5*60;
或
sleep
的返回值是睡眠的实际秒数。您可以检查此值并忽略任何异常大的值:
$success = 0;
$slept = 0;
while (($success == 0) && ($slept < 300)) {
$success = try_something();
if ($success == 0) {
$n = sleep 3;
if ($n <= 3) {
$slept += $n;
} else {
# looks like the clock just got updated
}
}
}
$success=0;
美元=0;
而($success==0)和($success<300)){
$success=尝试某事();
如果($success==0){
$n=睡眠3;
如果($n)那么使用系统正常运行时间呢?有一个Perl模块返回一个int
值,表示正常运行时间(秒)。很好!闹钟()做得很好。它不受外部时钟变化的影响。谢谢。这不是一个真正的解决方案,因为请尝试一下()完成大约需要5秒钟。然后在一些时间检查中换行尝试某事
,例如,$t=time;$success=try\u something();$t2=time-$t;if($t2
$success = 0;
$slept = 0;
while (($success == 0) && ($slept < 300)) {
$success = try_something();
if ($success == 0) {
$n = sleep 3;
if ($n <= 3) {
$slept += $n;
} else {
# looks like the clock just got updated
}
}
}