Monks,

I have a daemon that runs in a loop which is driven by a poll on several sockets, and a bunch of timers that go off on various intervals. I have implemented a simple timer mechanism by keeping a hash of timers, where each timer is represented by a code-ref for the function that should be called when the timer goes off, and the next time when the counter should go off. This is calculated by adding the timer's interval to the current time as returned by time(). This works great, except when someone changes the system clock... then all my timers are hopelessly out of whack!

So, I want to keep my current code as unchanged as possible, but insulate myself from system-clock changes. What suggestions do my fellow monks have for getting a tick every second without calling time()? I banged out the following code as a first shot:

my $counter; init_timer(); while(1) { select(undef, undef, undef, 0.5); print "$counter " . scalar(localtime) . "\n"; } sub init_timer { $counter = 0; $SIG{ALRM} = \&tick; alarm(1); } sub tick { alarm(1); $counter++; }

This seems to work, but I don't know if it is a good/safe way to do it... is it okay to set a new alarm from within the SIGALRM signal handler? Are there any other gotchas (besides not being able to intermix any sleep() calls in my program, which I don't do anyway)? Will it pretty reliably give me a tick every second (I don't need anything terribly HiRes at this point... if I ever do, I suppose it wouldn't be too hard to retrofit it with Time::HiRes...)

TIA

--
3dan

In reply to system-clock-safe timers without time()? by edan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.