Generally if I have a monolithic process that I'm using to watch for events on a filehandle *and* handle timed events simultaneously, I'll just build that into the process's event loop:
sub event_loop {
my $next_event = &get_next_event; # e.g. time() + 5
if (select($rh, $wh, $eh, $next_event - time())) {
&process($rh, $wh, $eh);
} elsif ($next_event <= time()) {
&do_timed_events;
}
}
&event_loop while $running;
If you're using a
forking model, you may need to provide some additional information. Is each child process dedicated to handling one specific timed event, or do you have an existing pool of forked processes doing their own thing, and you just don't care if one of them handles the timed event?
If you have one or more children that are guaranteed to be running, just assign out your timed event to the first child:
if (fork()) {
$children_spawned++;
return 1;
} else {
# Here, the *very first* child won't have $children_spawned
unless ($children_spawned) {
print "I'm the first!\n";
&do_main_with_timed_event_processing;
} else {
&do_main_without_timed_events;
}
}
If that first process isn't guaranteed to be running, you may just need some inter-process communication between your children. Whoever steps up to the plate first to handle a timed event gets it. This can be done with shared memory or semaphores. See
perlipc for more information.