in reply to The most precise second (timer)
If the concern is first ensuring errors don't accumulate and second an emphasis on minimum variation in period then the following code should help:
use strict; use warnings; use Time::HiRes qw/time sleep/; my $nextTick = int (time()); while (1) { $nextTick += 1.0; # We want to stuff again in 1 second my $wait = 0.99 - ($nextTick - time()); # allow 10ms slop in sleep + period sleep $wait if $wait > 0.0; 1 while time() < $nextTick; # spin until time is up RunStuff(); } sub RunStuff { # kick off required sub tasks here print time(), "\n"; }
The key is to calculate when the next interesting epoch is, then sleep for most of the time until then. The 1 while ... loop is a busy wait until the next epoch time has arrived.
|
|---|