Just one caveat when using sleep and usleep... you generally will want to use code like this:
my $time_to_sleep = ... # while ($time_to_sleep > 0) { $time_to_sleep = Time::HiRes::usleep($time_to_sleep); }
The use of signals in your program can cause sleep and usleep to return before the amount of time specified. Here's an example:
use Time::HiRes; $SIG{ALRM} = sub { warn "alarm went off" }; alarm(5); my $t = Time::HiRes::usleep(10_000_000); # 10 seconds print "done, t = $t\n";
The 'done' message is printed approx. 5 seconds into program execution.

Yet another implementation possibility is to use the OS's interval timers like this:

use Time::HiRes qw(setitimer ITIMER_VIRTUAL); my $state; $SIG{ALRM} = sub { if ($state == 0) { warn "starting application"; # start application here $state = 1; my $wait_time = 10; # compute time to wait here setitimer(ITIMER_REAL, $wait_time, 0); } else { warn "stopping application"; # stop application here $state = 2; setitimer(ITIMER_REAL, 0, 0); # disable interval timer } }; # wait for 5 seconds before starting app $state = 0; setitimer(ITIMER_REAL, 5, 0); while ($state != 2) { # do other stuff... }
This is more of a multi-threaded approach which allows you to perform other tasks during the wait periods.

In reply to Re^2: Alternatives for "sleepy" while loop by pc88mxer
in thread Alternatives for "sleepy" while loop by walto

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.