如何处理队列中的所有项目并退出


How to process all items in queue and exit

我在运行Ubuntu的LAMP堆栈服务器上使用Laravel 5。我正在使用排队系统:

http://laravel.com/docs/master/queues

我可以从文档中看到,有能力运行队列:侦听,它将永远侦听并处理队列中过去和未来的项目。

还有队列:只处理队列中第一个项目的工作。

有没有办法只处理队列中的每一项,然后停止侦听?

我只想定期处理队列,所以我如何设置一个cron作业来处理队列,然后在队列中的所有内容都完成后立即退出?

我也只是在看这个。我修改了内置的queue:work命令来处理整个队列并退出。

php手工制作:控制台ProcessQueueAndExit

您可以在获取代码https://gist.github.com/jdforsythe/b8c9bd46250ee23daa9de15d19495f07

或者就在这里,为了永恒:

namespace App'Console'Commands;
use Illuminate'Console'Command;
use Carbon'Carbon;
use Illuminate'Queue'Worker;
use Illuminate'Contracts'Queue'Job;
use Symfony'Component'Console'Input'InputOption;
use Symfony'Component'Console'Input'InputArgument;
class ProcessQueueAndExit extends Command {
  protected $signature = 'queue:workall {connection?} {--queue=} {--daemon} {--delay=} {--force} {--memory=} {--sleep=} {--tries=}';
  protected $description = 'Process all jobs on a queue and exit';
  protected $worker;
  public function __construct(Worker $worker) {
    parent::__construct();
    $this->worker = $worker;
  }
  public function handle() {
    if ($this->downForMaintenance() && ! $this->option('daemon')) {
      return $this->worker->sleep($this->option('sleep'));
    }
    $queue = $this->option('queue');
    $delay = $this->option('delay');
    $memory = $this->option('memory');
    $connection = $this->argument('connection');
    // keep processing until there are no more jobs returned
    do {
      $response = $this->runWorker(
        $connection, $queue, $delay, $memory, $this->option('daemon')
      );
      if (! is_null($response['job'])) {
        $this->writeOutput($response['job'], $response['failed']);
      }
    } while (! is_null($response['job']));
  }
  protected function runWorker($connection, $queue, $delay, $memory, $daemon = false) {
    if ($daemon) {
      $this->worker->setCache($this->laravel['cache']->driver());
      $this->worker->setDaemonExceptionHandler(
        $this->laravel['Illuminate'Contracts'Debug'ExceptionHandler']
      );
      return $this->worker->daemon(
        $connection, $queue, $delay, $memory,
        $this->option('sleep'), $this->option('tries')
      );
    }
    return $this->worker->pop(
      $connection, $queue, $delay,
      $this->option('sleep'), $this->option('tries')
    );
  }
  protected function writeOutput(Job $job, $failed) {
    if ($failed) {
      $this->output->writeln('<error>['.Carbon::now()->format('Y-m-d H:i:s').'] Failed:</error> '.$job->getName());
    }
    else {
      $this->output->writeln('<info>['.Carbon::now()->format('Y-m-d H:i:s').'] Processed:</info> '.$job->getName());
    }
  }
  protected function downForMaintenance() {
    if ($this->option('force')) {
        return false;
    }
    return $this->laravel->isDownForMaintenance();
  }
}

我在命令文件中使用这个:

$queue = Queue::connection('yourqueueconnection');
while ($entry = $queue->pop()) {
    // your task
}