需要每5秒运行一个子程序,但需要在系统时钟标记处测量.所以,需要开始于0,5,10,15 .... 45,50%,55其次,它每分钟(确切地,与0.1秒precistion).
就像是:
for(;;) {
do_sleep(); #time need to sleep to the next 5 second mark
run_this();
}
Run Code Online (Sandbox Code Playgroud)
所述run_this子可快可慢(其0.2之间运行时- 120秒).当它运行超过5秒时 - 无论其运行时间如何,下一次运行必须精确到5秒.
例如,当 run_this
问题是:如何编写do_sleep?
对于0.1s精度,您需要使用Time :: HiRes模块.就像是:
#!/usr/bin/perl
use 5.014;
use warnings;
use Time::HiRes qw(tv_interval usleep gettimeofday);
for(;;) {
do_sleep();
run_this();
}
sub do_sleep {
my $t = [gettimeofday];
my $next = (int($t->[0]/5) + 1) * 5;
my $delta = tv_interval ($t, [$next, 0]);
usleep($delta * 1_000_000);
return;
}
sub run_this {
my $t = [gettimeofday];
printf "Start is at: %s.%s\n",
scalar localtime $t->[0],
$t->[1];
usleep( rand 10_000_000 ); #simulating the runtime between 0-10 seconds (in microseconds)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
850 次 |
| 最近记录: |