From 23c10dfefc48f57491bd1c47d3f5679bd07445b8 Mon Sep 17 00:00:00 2001 From: Florian Pritz Date: Tue, 24 Jul 2018 10:47:45 +0200 Subject: Add interval timer snippet Signed-off-by: Florian Pritz --- interval-timer.pl | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 interval-timer.pl 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(); +} -- cgit v1.2.3-24-g4f1b