| 1 | package Daemonise::Plugin::Paralleliser; | ||
| 2 | |||
| 3 | use Mouse::Role; | ||
| 4 | |||
| 5 | # ABSTRACT: Daemonise plugin to parallelise certain tasks easily | ||
| 6 | |||
| 7 | use Parallel::ForkManager; | ||
| 8 | |||
| 9 | |||
| 10 | has 'worker' => ( | ||
| 11 | is => 'rw', | ||
| 12 | isa => 'Int', | ||
| 13 | default => sub { 5 }, | ||
| 14 | ); | ||
| 15 | |||
| 16 | |||
| 17 | has 'pm' => ( | ||
| 18 | is => 'rw', | ||
| 19 | isa => 'Parallel::ForkManager', | ||
| 20 | ); | ||
| 21 | |||
| 22 | |||
| 23 | after 'configure' => sub { | ||
| 24 | my ($self, $reconfig) = @_; | ||
| 25 | |||
| 26 | $self->log("configuring Paralleliser plugin") if $self->debug; | ||
| 27 | |||
| 28 | return; | ||
| 29 | }; | ||
| 30 | |||
| 31 | |||
| 32 | sub parallelise { | ||
| 33 | my ($self, $code, @input) = @_; | ||
| 34 | |||
| 35 | $self->pm(Parallel::ForkManager->new($self->worker)); | ||
| 36 | |||
| 37 | foreach my $input (@input) { | ||
| 38 | $self->pm->start and next; | ||
| 39 | |||
| 40 | # disable cron locking on configure and unlocking on destruction | ||
| 41 | $self->is_cron(0); | ||
| 42 | |||
| 43 | # reconfigure to setup eventually broken connections | ||
| 44 | $self->configure(1); | ||
| 45 | |||
| 46 | # do not respond to previously setup TERM and INT signal traps | ||
| 47 | $SIG{QUIT} = 'IGNORE'; ## no critic | ||
| 48 | $SIG{TERM} = 'IGNORE'; ## no critic | ||
| 49 | $SIG{INT} = 'IGNORE'; ## no critic | ||
| 50 | |||
| 51 | $code->($input); | ||
| 52 | |||
| 53 | $self->pm->finish; | ||
| 54 | } | ||
| 55 | $self->pm->wait_all_children; | ||
| 56 | |||
| 57 | return; | ||
| 58 | } | ||
| 59 | |||
| 60 | 1; | ||
| 61 | |||
| 62 | __END__ |