diff options
-rw-r--r-- | interval-timer.pl | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/interval-timer.pl b/interval-timer.pl new file mode 100644 index 0000000..f7bb247 --- /dev/null +++ b/interval-timer.pl @@ -0,0 +1,22 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +use Time::HiRes qw(sleep time gettimeofday); +use POSIX qw(fmod); + +my $interval = 1; + +# enable autoflush +$| = 1; + +while (1) { + my ($time, $usec) = gettimeofday(); + # this also works, but fmod below is more readable + #my $sleep_time = ($interval - ($time % $interval + 1)) + (1000_000 - $usec) / 1000_000; + my $sleep_time = $interval - fmod(time(), $interval); + printf "current time = %s (%s, %s), sleeping for %s\n", time(), $time, $usec, $sleep_time; + my $slept = sleep($sleep_time); + printf "new time = %s after sleeping for %s\n", time(), $slept; + printf "%s\n", time(); +} |