The use of signals in your program can cause sleep and usleep to return before the amount of time specified. Here's an example:my $time_to_sleep = ... # while ($time_to_sleep > 0) { $time_to_sleep = Time::HiRes::usleep($time_to_sleep); }
The 'done' message is printed approx. 5 seconds into program execution.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";
Yet another implementation possibility is to use the OS's interval timers like this:
This is more of a multi-threaded approach which allows you to perform other tasks during the wait periods.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... }
In reply to Re^2: Alternatives for "sleepy" while loop
by pc88mxer
in thread Alternatives for "sleepy" while loop
by walto
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |