From 64fd9ed4ed3ec6292ed881f37e279418ec52942e Mon Sep 17 00:00:00 2001 From: Kyle M Hall Date: Tue, 3 Jan 2023 15:35:42 +0000 Subject: [PATCH] Bug 32558: Add ability for background_jobs_worker.pl to process multiple jobs simultaneously up to a limit Right now background_jobs_worker.pl only processes jobs in serial. It would make sense to handle jobs in parallel up to a user definable limit. Test Plan: 1) Apply this patch 2) Stop background_jobs_worker.pl 3) Generate some background jobs by editing records, placing holds, etc 4) Watch processes in a new terminal: watch -n 0.1 'ps aux | grep background_jobs_worker.pl' 5) Run background_jobs_worker.pl 6) Note the multiple forked processes in the ps output --- misc/background_jobs_worker.pl | 29 +++++++++++------------------ 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/misc/background_jobs_worker.pl b/misc/background_jobs_worker.pl index eb36f34f964..37dd328655d 100755 --- a/misc/background_jobs_worker.pl +++ b/misc/background_jobs_worker.pl @@ -52,11 +52,14 @@ use JSON qw( decode_json ); use Try::Tiny qw( catch try ); use Pod::Usage; use Getopt::Long; +use Parallel::ForkManager; use Koha::BackgroundJobs; my ( $help, @queues ); +my $max_processes = 10; GetOptions( + 'm|max-processes=i' => \$max_processes, 'h|help' => \$help, 'queue=s' => \@queues, ) || pod2usage(1); @@ -74,6 +77,8 @@ try { warn sprintf "Cannot connect to the message broker, the jobs will be processed anyway (%s)", $_; }; +my $pm = Parallel::ForkManager->new($max_processes); + if ( $conn ) { # FIXME cf note in Koha::BackgroundJob about $namespace my $namespace = C4::Context->config('memcached_namespace'); @@ -96,32 +101,20 @@ while (1) { # It could work in a first step, but then we will want to handle job that will be created from the message received my $job = Koha::BackgroundJobs->find($args->{job_id}); - process_job( $job, $args ); + $pm->start and next; + $job->process( { job_id => $job->id, %$args } ); $conn->ack( { frame => $frame } ); # FIXME depending on success? + $pm->finish; } else { my $jobs = Koha::BackgroundJobs->search({ status => 'new', queue => \@queues }); while ( my $job = $jobs->next ) { + $pm->start and next; my $args = $job->json->decode($job->data); - process_job( $job, { job_id => $job->id, %$args } ); + $job->process( { job_id => $job->id, %$args } ); + $pm->finish; } sleep 10; } } $conn->disconnect; - -sub process_job { - my ( $job, $args ) = @_; - - my $pid; - if ( $pid = fork ) { - wait; - return; - } - - die "fork failed!" unless defined $pid; - - $job->process( $args ); - - exit; -} -- 2.37.1