Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save crishoj/79c6a708dbd90ada4b5f3911c473baf2 to your computer and use it in GitHub Desktop.
Save crishoj/79c6a708dbd90ada4b5f3911c473baf2 to your computer and use it in GitHub Desktop.
Ensure that the Laravel 5.5 queue worker is running with "php artisan queue:checkup" and restart it if necessary. You can run this automatically with a cron job: http://laravel.com/docs/scheduling
#!/bin/bash
#
# You can run this bash script with a cron job
# or just run the command below.
#
php /path/to/artisan schedule:run >/dev/null 2>&1
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class EnsureQueueWorkerIsRunning extends Command
{
protected $signature = 'queue:checkup';
protected $description = 'Ensure that the queue worker is running.';
protected $pidFile;
public function handle()
{
$this->pidFile = storage_path('app/queue.pid');
if (! $this->isWorkerRunning()) {
$this->comment('Queue worker is being started.');
$pid = $this->startWorker();
$this->saveWorkerPID($pid);
}
$this->comment('Queue worker is running.');
}
/**
* Check if the queue worker is running.
*/
private function isWorkerRunning(): bool
{
if (! $pid = $this->getLastWorkerPID()) {
return false;
}
$process = exec("ps -p {$pid} -opid=,command=");
$processIsQueueWorker = str_contains($process, 'queue:work');
return $processIsQueueWorker;
}
/**
* Get any existing queue worker PID.
*/
private function getLastWorkerPID()
{
if (! file_exists($this->pidFile)) {
return false;
}
return file_get_contents($this->pidFile);
}
/**
* Save the queue worker PID to a file.
*/
private function saveWorkerPID($pid)
{
file_put_contents($this->pidFile, $pid);
}
/**
* Start the queue worker.
*/
private function startWorker(): int
{
$command = 'php ' . base_path('artisan') . ' queue:work --sleep=1 --tries=3 > /dev/null & echo $!';
$pid = exec($command);
return $pid;
}
}
<?php
namespace App\Console;
use App\Console\Commands\EnsureQueueWorkerIsRunning;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
EnsureQueueWorkerIsRunning::class
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
*
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('queue:checkup')->everyFiveMinutes();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment