Async-Event-Interval
view release on metacpan or search on metacpan
lib/Async/Event/Interval.pm view on Meta::CPAN
my ($self) = @_;
if (! exists $self->{pm}) {
$self->{pm} = Parallel::ForkManager->new(1);
}
return $self->{pm};
}
sub _pid {
my ($self, $pid) = @_;
if (defined $pid) {
$self->{pid} = $pid;
$events{$self->id}->{pid} = $self->{pid};
}
return $self->{pid} || undef;
}
sub _rand_shm_key {
my $key_str;
for (0..11) {
srand();
$key_str .= ('A'..'Z')[rand(26)];
}
return $key_str;
}
sub _rand_shm_lock {
# Used for the 'protected' option in the %events hash creation
srand();
return int(rand(1_000_000));
}
sub _runs {
my ($self, $increment) = @_;
$events{$self->id}->{runs}++ if defined $increment;
return $events{$self->id}->{runs};
}
sub _setup {
my ($self, $interval, $cb, @args) = @_;
$self->interval($interval);
$self->_cb($cb);
$self->_args(\@args);
}
sub _shm_lock {
return $shared_memory_protect_lock;
}
sub _started {
my ($self, $started) = @_;
$self->{started} = $started if defined $started;
return $self->{started};
}
sub DESTROY {
if (defined $_[0]) {
$_[0]->stop if $_[0]->pid;
}
# On events with interval of zero, ForkManager runs finish(), which
# calls our destroy method. We only want to blow away the %events
# hash if we truly go out of scope
return if (caller())[0] eq 'Parallel::ForkManager::Child';
delete $events{$_[0]->id};
}
sub _end {
if (! keys %events) {
IPC::Shareable::clean_up_protected(_shm_lock());
}
}
END {
_end();
}
sub _vim{}
1;
__END__
=head1 NAME
Async::Event::Interval - Scheduled and one-off asynchronous events
=for html
<a href="https://github.com/stevieb9/async-event-interval/actions"><img src="https://github.com/stevieb9/async-event-interval/workflows/CI/badge.svg"/></a>
<a href='https://coveralls.io/github/stevieb9/async-event-interval?branch=master'><img src='https://coveralls.io/repos/stevieb9/async-event-interval/badge.svg?branch=master&service=github' alt='Coverage Status' /></a>
=head1 SYNOPSIS
A simple event that updates JSON data from a website using a shared scalar
variable, while allowing the main application to continue running in the
foreground. Multiple events can be simultaneously used if desired.
See L</EXAMPLES> for other various functionality of this module.
use warnings;
use strict;
use Async::Event::Interval;
my $event = Async::Event::Interval->new(2, \&callback);
my $json = $event->shared_scalar;
$event->start;
while (1) {
print "$$json\n";
#... do other things
$event->restart if $event->error;
}
sub callback {
$$json = ...; # Fetch JSON from website
}
=head1 DESCRIPTION
Very basic implementation of asynchronous events triggered by a timed interval.
( run in 0.749 second using v1.01-cache-2.11-cpan-75ffa21a3d4 )