[Israel.pm] $SIG{ALRM} and alarm.

Oron Peled oron at actcom.co.il
Fri Jun 1 04:18:55 PDT 2007


On Thursday, 31 בMay 2007 12:27, Yosef Meller wrote:
> ציטוט Meron Cohen:
> > ... I'm trying to implement 2 timers in a script....
> On Unix you setitimer (in Time::HiRes)

It doesn't solve Meron's original problem since there's also a
single interval-timer.

Aside from high level wrappers mentioned by others, I'd like to
remind that Unix/Linux alarm(2) system call does two things:
  - Set a new alarm timer.
  - Returns the time remaining to the expiry of the old timer
    (if there was any).

An example:
 perl -e '$x=alarm(6); sleep(2); $y=alarm(12); print "x=$x, y=$y\n"'
 x=0, y=4

So wrappers that want to implement multiple timers abstraction should
maintain a list of timers (one famous form is in sorted deltas queue)
and use alarm to schedule the next alarm call.

In the $SIG{ALRM} handler the wrapper would schedule the next pending
timer and call some user defined function.

Example (not tested) handler code:

sub our_alarm_handler {
	$this = shift @delta_queue;
	$func = $this->{FUNC};
	$data = $this->{DATA};
	$delta = $this->{DELTA};
	$next = $delta_queue[0];
	alarm $next->{DELTA};
	&$func($data);
}

The code to compute the DELTA and insert new timers into the queue
are left as an exercise...

Bye,

-- 
Oron Peled                             Voice/Fax: +972-4-8228492
oron at actcom.co.il                  http://www.actcom.co.il/~oron
ICQ UIN: 16527398

"In fact, one of the saddest but most common conditions in elementary
school computer labs ..., is the children are being trained to use
Word, Excel and PowerPoint. I consider that criminal, because children
should be making things, communicating, exploring, sharing, not
running office automation tools."   -- Nicholas Negroponte



More information about the Perl mailing list