Skip to content

Instantly share code, notes, and snippets.

@goran-popovic
Last active February 25, 2024 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goran-popovic/2aac3715ce25588941e23889b44c88ba to your computer and use it in GitHub Desktop.
Save goran-popovic/2aac3715ce25588941e23889b44c88ba to your computer and use it in GitHub Desktop.
Running custom Artisan commands with Supervisor - Basic Example (https://geoligard.com/running-custom-artisan-commands-with-supervisor)
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
class MonitorOrders extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'orders:monitor
{--max-jobs=100 : The number of jobs to process before stopping}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Monitor pending tool orders and dispatch them for processing.';
/**
* Execute the console command.
*/
public function handle()
{
$jobsProcessed = 0;
$maxJobs = $this->option('max-jobs');
while (true) {
// Get all the orders with the pending status
$orders = Order::where('status', 'pending')->get();
// If there are no orders with a pending status wait for a second then check again
if ($orders->doesntExist()) {
sleep(1);
continue;
}
foreach ($orders as $order) {
// Dispatch the order for further processing to a job
ProcessOrder::dispatch($order)
->onQueue('orders')
->onConnection('database');
// Increase the number of processed jobs
$jobsProcessed++;
// Stop the command if the number of jobs reaches the maximum number set
if($jobsProcessed >= $maxJobs) {
return 0; // Success
}
// Get the restart command value from the cache
$restartCommand = Cache::get('orders:restart', false);
// Stop the command if needed and remove the entry from the cache
if($restartCommand) {
Cache::forget('orders:restart');
return 0; // Success
}
}
sleep(1); // Take a break between runs
}
}
}
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
class RestartOrders extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'orders:restart';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Restart orders monitor command after the current job.';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
Cache::forever('orders:restart', true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment