Async-Event-Interval
view release on metacpan or search on metacpan
lib/Async/Event/Interval.pm view on Meta::CPAN
}
=head2 Shared data across events
This software uses L<IPC::Shareable> internally, so it's automatically
installed for you already. You can use shared data for use across many processes
and events, and if you use the same IPC key, even across multiple scripts.
Here's an example that uses a hash that's stored in shared memory, where the
parent process (the script) and two other processes (the two events) all share
and update the same hash.
B<Important>: keep shared hash values flat (strings, numbers). Nested data
structures (e.g. C<< $hash{$$}{key} >>) cause L<IPC::Shareable> to create
child shared-memory segments whose ownership can conflict across forked
processes, leading to data loss. For per-event shared data, consider
L</shared_scalar> instead.
use Async::Event::Interval;
use IPC::Shareable;
tie my %shared_data, 'IPC::Shareable', {
key => '123456789',
create => 1,
destroy => 1
};
$shared_data{$$}++;
my $event_one = Async::Event::Interval->new(0.2, \&update);
my $event_two = Async::Event::Interval->new(1, \&update);
$event_one->start;
$event_two->start;
sleep 10;
$event_one->stop;
$event_two->stop;
for my $pid (keys %shared_data) {
printf(
"Process ID %d executed %d times\n",
$pid,
$shared_data{$pid}
);
}
for my $event ($event_one, $event_two) {
printf(
"Event ID %d with PID %d ran %d times, with %d errors and an interval" .
" of %.2f seconds\n",
$event->id,
$event->pid,
$event->runs,
$event->errors,
$event->interval
);
}
sub update {
# Because each event runs in its own process, $$ will be set to the
# process ID of the calling event, even though they both call this
# same function
$shared_data{$$}++;
}
=head2 Event error management
If an event crashes, print out error information and restart the event.
This example shows how to print the most recent error message and halt the
program so you can troubleshoot your callback if your event crashes five or more
times.
use Async::Event::Interval;
my $event = Async::Event::Interval->new(5, sub {print "hey\n";});
$event->start;
while (1) {
#... do stuff
if ($event->errors >= 5) {
print $event->error_message;
exit;
}
if ($event->error) {
printf(
"Runs: %d, Runs errored: %d, Last error message: %s\n",
$event->runs,
$event->errors,
$event->error_message
);
$event->restart;
}
}
=head2 Event crash: Restart event
use warnings;
use strict;
use Async::Event::Interval;
# kill 9, $$ is a contrived self-kill to demonstrate crash detection
my $event = Async::Event::Interval->new(0.5, sub { kill 9, $$; });
$event->start;
sleep 1; # Do stuff
if ($event->error) {
print "Event crashed, restarting\n";
$event->restart;
( run in 2.573 seconds using v1.01-cache-2.11-cpan-df04353d9ac )