chromatic has asked for the wisdom of the Perl Monks concerning the following question:
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; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
RE: Using Alarm to Handle Timing
by awwaiid (Friar) on Jul 21, 2000 at 00:57 UTC | |
by merlyn (Sage) on Jul 21, 2000 at 07:53 UTC | |
by chromatic (Archbishop) on Jul 21, 2000 at 01:05 UTC | |
|
RE: Using Alarm to Handle Timing
by merlyn (Sage) on Jul 21, 2000 at 07:52 UTC |