summaryrefslogtreecommitdiffstats
path: root/interval-timer.pl
blob: f7bb24704c4b6f8829ccaa3cb0aeb8a13fda4083 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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();
}