From 180dd6547c63393770f60f0e2832c8087f982e5d Mon Sep 17 00:00:00 2001 From: Frederic Guillot Date: Sun, 1 May 2016 23:08:03 -0400 Subject: [PATCH] Added option to stop worker when the queue is empty --- worker.php | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/worker.php b/worker.php index 59418e0..b1f2802 100644 --- a/worker.php +++ b/worker.php @@ -8,11 +8,37 @@ if (php_sapi_name() !== 'cli') { die('This script can run only from the command line.'.PHP_EOL); } +$options = getopt('', array( + 'stop', +)); + +function check_job_left(Pheanstalk $connection, array $options) +{ + if (isset($options['stop'])) { + $queues = $connection->listTubes(); + + if (in_array(BEANSTALKD_QUEUE, $queues)) { + $stats = $connection->statsTube(BEANSTALKD_QUEUE); + echo 'Jobs in queue: '.$stats->current_jobs_ready.PHP_EOL; + (int) $stats->current_jobs_ready === 0 && exit(0); + } else { + echo 'No queue'.PHP_EOL; + exit(0); + } + } +} + $connection = new Pheanstalk(BEANSTALKD_HOST); +check_job_left($connection, $options); + while ($job = $connection->reserveFromTube(BEANSTALKD_QUEUE)) { $feed_id = $job->getData(); + echo 'Processing feed_id='.$feed_id.PHP_EOL; + Model\Feed\refresh($feed_id); $connection->delete($job); + + check_job_left($connection, $options); }