As the Perl threads implementation is still undergoing renovation, I've considered other approaches for handling issues of concurrency.

In one of my programs, it would be very useful to have certain tasks executed at certain times. Low-latency and real-time responses aren't critical, but if they happen within a few seconds either way, I'm happy.

Here's an approach I'm testing. Things work fine with my test, but I'd like to know if there are any problems with my concept or execution. Alternately, if there's a better way to do this, feel free to let me know. (Using a separate process or cron is a possibility, but it hampers porting, which is important with this project).

#!/usr/bin/perl -w use strict; # we're abusing signals for this trick $SIG{ALRM} = \&wake_up; start(); sub start { # arbitrary number, could be a variable alarm(5); while (1) { # random time so the handler executes in different spots sleep int rand(3); print "Here's a line after a sleep.\n"; sleep int rand(3); print "Here's a line after another sleep.\n"; # don't interrupt this chunk my $hold = alarm(0); print "Suspending alarm with $hold second(s) left.\n"; sleep int rand(3); print "There should never be an alarm right before this.\n"; # interruptions okay now alarm($hold); sleep int rand(3); print "This is the last line of the loop.\n\n"; } } sub wake_up { # don't interrupt the interrupt (probably unnecessary) $SIG{ALRM} = 'ignore'; print "\t=> in alarm handler <=\n"; # reset alarm alarm(5); # reinstall handler $SIG{ALRM} = \&wake_up; }

In reply to Using Alarm to Handle Timing by chromatic

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.