summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorFlorian Pritz <bluewind@xinu.at>2018-07-24 10:47:45 +0200
committerFlorian Pritz <bluewind@xinu.at>2018-07-24 10:47:45 +0200
commit23c10dfefc48f57491bd1c47d3f5679bd07445b8 (patch)
tree667873b131c95c01a0508ee591bad94dfe0abf3e
parent719cfbd01026cf623b5cada51924d5969f2a743b (diff)
downloadbin-23c10dfefc48f57491bd1c47d3f5679bd07445b8.tar.gz
bin-23c10dfefc48f57491bd1c47d3f5679bd07445b8.tar.xz
Add interval timer snippet
Signed-off-by: Florian Pritz <bluewind@xinu.at>
-rw-r--r--interval-timer.pl22
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();
+}