in reply to Re^2: making a loop script with a remote URL call faster
in thread making a loop script with a remote URL call faster
More exact timing can be achieved by properly calculating the interval. This is a rough sketch, taken from memory
#/usr/bin/env perl use strict; use warnings; # We need sub-second precision here :-) use Time::HiRes wq(time sleep); my $lastrun = 0; while(1) { # Time consuming stuff here my $now = time; # Calculate the time we need to sleep. First we calculate the dif +ference between now and the last run. # That's how long the last run took. Now, calculate how many seco +nds remaining in the current minute. # If the answer is negative, one of two things happened: Either i +t's our first run, or the last run took # longer than a minute my $sleeptime = 60 - ($now - $lastrun); if($sleeptime > 0) { sleep($sleeptime); } $lastrun = $now; }
If you want the code to run at a specific second in every minute, you could also do that. Again, this is untested and from memory:
#/usr/bin/env perl use strict; use warnings; # We need sub-second precision here :-) use Time::HiRes wq(time sleep); my $activesecond = 42; # Run whenever the seconds are "42" while(1) { my $now = time; # The built-in modulus function converts to integer, # which would introduce jitter of up to nearly a second. # So, out with the traditional: # my $cursecond = $now % 60; # ...and in with the more manual version: my $cursecond = $now - (60.0 * int($now / 60.0)); if($cursecond != $activesecond) { # Need to wait my $sleeptime = $activesecond - $cursecond; if($sleeptime < 0) { # Handle rollover $sleeptime += 60.0; } sleep($sleeptime); } # Time consuming stuff here }
Hope that helps a bit.
Edit: If, for some strange reason you need to use International Atomic Time, you need to take the UTC/TAI offset into account. This is currently 37 seconds, but you will need to consult the IERS Bulletin C twice a year to check for leap second announcements. But in essence, all you need to do is add the appropriate offset when assigning $now:
my $taioffset = 37; ... my $now = $time + $taioffset;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: making a loop script with a remote URL call faster
by cavac (Prior) on Jan 16, 2022 at 21:04 UTC | |
by haukex (Archbishop) on Jan 18, 2022 at 13:41 UTC | |
by LanX (Saint) on Jan 16, 2022 at 23:43 UTC | |
by cavac (Prior) on Jan 17, 2022 at 15:47 UTC | |
by LanX (Saint) on Jan 17, 2022 at 17:17 UTC |