|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Resque\Reserver; |
| 4 | + |
| 5 | +use Resque_Job; |
| 6 | +use Psr\Log\LoggerInterface; |
| 7 | + |
| 8 | +/** |
| 9 | + * BlockingListPopReserver uses the blocking list pop command in redis (https://redis.io/commands/blpop) to wait for a |
| 10 | + * job to become available on any of the given queues. |
| 11 | + * This also behaves similarly to QueueOrderReserver in that the queues are checked in the order they are given. |
| 12 | + * |
| 13 | + * Environment variables: |
| 14 | + * - BLPOP_TIMEOUT: The maximum time in seconds that the bplop command should block while waiting for a job. |
| 15 | + * upon timeout, the worker will attempt to immediately reserve a job again. If zero is specified, the command will |
| 16 | + * block indefinitely. If not specified, the value of the INTERVAL variable will be used which defaults to 5 seconds. |
| 17 | + */ |
| 18 | +class BlockingListPopReserver extends AbstractReserver implements ReserverInterface |
| 19 | +{ |
| 20 | + /** @var int */ |
| 21 | + const DEFAULT_TIMEOUT = 5; |
| 22 | + |
| 23 | + /** |
| 24 | + * @param LoggerInterface $logger |
| 25 | + * @param array $queues The queues to reserve from. If null, then the queues are retrieved dynamically from redis |
| 26 | + * on each call to reserve(). |
| 27 | + * @param int $timeout The number of seconds to wait for a job to be enqueued. A timeout of zero will block |
| 28 | + * indefinitely. |
| 29 | + */ |
| 30 | + public function __construct(LoggerInterface $logger, array $queues, $timeout = self::DEFAULT_TIMEOUT) |
| 31 | + { |
| 32 | + $this->timeout = $timeout; |
| 33 | + parent::__construct($logger, $queues); |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * {@inheritDoc} |
| 38 | + */ |
| 39 | + public function reserve() |
| 40 | + { |
| 41 | + $job = Resque_Job::reserveBlocking($this->getQueues(), $this->timeout); |
| 42 | + if ($job) { |
| 43 | + $this->logger->info("[{reserver}] Found job on queue '{queue}'", array( |
| 44 | + 'queue' => $job->queue, |
| 45 | + 'reserver' => $this->getName(), |
| 46 | + )); |
| 47 | + return $job; |
| 48 | + } |
| 49 | + return null; |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * {@inheritDoc} |
| 54 | + */ |
| 55 | + public function waitAfterReservationAttempt() |
| 56 | + { |
| 57 | + return false; |
| 58 | + } |
| 59 | +} |
0 commit comments