I was wondering how one may perform a given action every x seconds (or other, perhaps smaller) unit of time. My most logical answer is using Time::HiRes to sleep for x milliseconds, minus the ones the action took us to perform. This involves getting the current time a lot, to see how late we are, and all that.
Operations are possibly blocking, so they may take quite a bit of real time. Doing that seems ridiculusly wasteful, because there are so many system calls. But there is a reason - accuracy can fluxuate, but shouldn't accumilate fluxuations - simply sleeping for a constant time unit is not an option. In other words i'd like the script to correct it's timed interval so that it's somewhat in sync with the system clock.
My idea was something like this (say we want every second, maintaining relative accuracy for periods of a year or so):
my $x = 10; # the number of iterations to do between each sync
my $int = 10; # the desired interval between actions
my $y = 0; # another iteration limit, for catching up
foo: {
my $time = time();
for (my $i = 0; $i <= $y; $i++){ # catch up with real time from th
+e last loop
action(); # perform the action
}
for (my $i = 0; $i < $x; $i++){
action();
sleep $int;
}
my $ntime = time();
$y = int ( ($ntime - $time - $x * $int) / $int ); # calculate how
+many we missed, and round down
redo foo;
}
Any suggestions?
-nuffin
zz zZ Z Z #!perl
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.