More exact timing can be achieved by properly calculating the interval. This is a rough sketch, taken from memory
#/usr/bin/env perl
use strict;
use warnings;
# We need sub-second precision here :-)
use Time::HiRes wq(time sleep);
my $lastrun = 0;
while(1) {
# Time consuming stuff here
my $now = time;
# Calculate the time we need to sleep. First we calculate the dif
+ference between now and the last run.
# That's how long the last run took. Now, calculate how many seco
+nds remaining in the current minute.
# If the answer is negative, one of two things happened: Either i
+t's our first run, or the last run took
# longer than a minute
my $sleeptime = 60 - ($now - $lastrun);
if($sleeptime > 0) {
sleep($sleeptime);
}
$lastrun = $now;
}
If you want the code to run at a specific second in every minute, you could also do that. Again, this is untested and from memory:
#/usr/bin/env perl
use strict;
use warnings;
# We need sub-second precision here :-)
use Time::HiRes wq(time sleep);
my $activesecond = 42; # Run whenever the seconds are "42"
while(1) {
my $now = time;
# The built-in modulus function converts to integer,
# which would introduce jitter of up to nearly a second.
# So, out with the traditional:
# my $cursecond = $now % 60;
# ...and in with the more manual version:
my $cursecond = $now - (60.0 * int($now / 60.0));
if($cursecond != $activesecond) {
# Need to wait
my $sleeptime = $activesecond - $cursecond;
if($sleeptime < 0) {
# Handle rollover
$sleeptime += 60.0;
}
sleep($sleeptime);
}
# Time consuming stuff here
}
Hope that helps a bit.
Edit: If, for some strange reason you need to use International Atomic Time, you need to take the UTC/TAI offset into account. This is currently 37 seconds, but you will need to consult the IERS Bulletin C twice a year to check for leap second announcements. But in essence, all you need to do is add the appropriate offset when assigning $now:
my $taioffset = 37;
...
my $now = $time + $taioffset;
perl -e 'use Crypt::Digest::SHA256 qw[sha256_hex]; print substr(sha256_hex("the Answer To Life, The Universe And Everything"), 6, 2), "\n";'
|