我需要在while循环中每5分钟检查一些变量。 while循环也执行其他东西,但在该持续时间内,它必须每5分钟执行一次[code]。有人能建议我很好的解决方案吗?
while (1) {
<execute something all the time>
# Check the time, if it is 5 minutes passed then execute the below code
[code]
}
答案 0 :(得分:6)
#!/usr/bin/perl
use strict;
use warnings;
my $nextruntime=0;
while(1){
# Other stuff
if(time()>=$nextruntime){
print "Doing 5 minute stuff...\n";
# do your 5 minute stuff
$nextruntime=time()+300;
}
print "Waiting for Godot...\n";
sleep 1;
}
更改“my $ nextruntime = 0;”进入“我的$ nextruntime = time()+ 300;”如果您不想立即执行其他操作,程序将启动,但仅在最初的5分钟后才会启动。
答案 1 :(得分:3)
您可以使用alarm
功能:
my $foo = 0;
local $SIG{ALRM} = sub {
say($foo);
alarm(1);
};
alarm(1);
while (1) {
$foo++;
}
答案 2 :(得分:0)
my $next_5min_sec = time() + 5 * 60;
while(1)
{
# some other stuff
$t = time();
if ($t >= $next_5min_sec)
{
$next_5min_sec += 5 * 60;
# do your 5 minute stuff here
}
sleep(1);
}