<?php
/**
* Task Queue Batch Processor CLI
*/
require_once 'vendor/autoload.php'; // Autoload Composer dependencies
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use League\Queue\Laravel\LaravelQueue; //Example Queue implementation
class BatchProcessorCommand extends Command
{
protected $name = 'batch-process';
protected $description = 'Processes tasks from a queue in batches.';
private $queue;
private $batchSize;
public function __construct(LaravelQueue $queue, $batchSize = 10)
{
parent::__construct();
$this->queue = $queue;
$this->batchSize = $batchSize;
}
/**
* Set the batch size.
*
* @param string $batchSize
* @return void
*/
public function setBatchSize(string $batchSize)
{
$this->batchSize = (int)$batchSize;
}
/**
* Define the command arguments.
*
* @param InputInterface $input
* @param OutputInterface $output
* @return void
*/
protected function defineArguments(InputInterface $input, OutputInterface $output)
{
$output->registerArgument('batch-size', 'The number of tasks to process in each batch (default: 10)', 1);
}
/**
* Execute the command.
*
* @param InputInterface $input
* @param OutputInterface $output
* @return void
*/
public function run(InputInterface $input, OutputInterface $output)
{
$output->writeln('<info>Starting batch processing...</info>');
try {
$this->processQueueInBatches();
} catch (\Exception $e) {
$output->writeln('<error>Error during batch processing: ' . $e->getMessage() . '</error>');
}
$output->writeln('<info>Batch processing completed.</info>');
}
private function processQueueInBatches()
{
$queue = $this->queue;
while (true) {
$tasks = $queue->getTasks($this->batchSize);
if (empty($tasks)) {
break; // No more tasks in the queue
}
$output->writeln('<info>Processing batch of ' . count($tasks) . ' tasks...</info>');
foreach ($tasks as $task) {
try {
$task->process(); // Execute the task
} catch (\Exception $e) {
$output->writeln('<error>Error processing task ' . $task->id . ': ' . $e->getMessage() . '</error>');
// Optionally, handle task failures (e.g., retry, log to a dead-letter queue)
}
}
}
}
}
// Create the console application
$application = new Application();
$application->addCommand(new BatchProcessorCommand(new LaravelQueue()));
$application->run();
?>
Add your comment