PHP code example of berlioz / queue-manager

1. Go to this page and download the library: Download berlioz/queue-manager library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

berlioz / queue-manager example snippets


use Berlioz\QueueManager\Job\JobHandlerManager;

$manager = new JobHandlerManager($container, $defaultHandler);
$manager->addHandler('email', EmailJobHandler::class);
$manager->addHandler('report', ReportJobHandler::class);

$job = new Job('email'); // Example job with name 'email'
$manager->handle($job); // Delegates to EmailJobHandler

use Berlioz\QueueManager\Handler\JobHandlerInterface;
use Berlioz\QueueManager\Job\JobInterface;
use Berlioz\QueueManager\Exception\QueueManagerException;

class FooJobHandler implements JobHandlerInterface
{
    public function handle(JobInterface $job): void
    {
        if ($job->getName() !== 'foo') {
            throw new QueueManagerException('Invalid job name');
        }

        // Process the job
        $payload = $job->getPayload();
        echo "Processing job 'foo' with payload: " . json_encode($payload);
    }
}

use Berlioz\QueueManager\Queue\MemoryQueue;
use Berlioz\QueueManager\Worker;
use Berlioz\QueueManager\WorkerOptions;
use Berlioz\QueueManager\Handler\JobHandlerManager;
use Psr\Log\NullLogger;

// Create a Job Handler Manager
$jobHandler = new JobHandlerManager($container);

// Initialize the Worker
$worker = new Worker($jobHandler);

// Optionally, set a logger
$worker->setLogger(new NullLogger());

// Configure worker options
$options = new WorkerOptions(
    name: 'worker',   // Worker name
    limit: 10,        // Max jobs to execute
    memoryLimit: 128, // Memory limit in MB
    timeLimit: 60,    // Time limit in seconds
    killFilePath: 10, // File to kill process
    stopNoJob: true,  // Stop if no job
    sleep: 2          // Sleep time between jobs in seconds
);

// Create a queue instance
$queue = new MemoryQueue();

// Run the worker
$exitCode = $worker->run($queue, $options);

use Berlioz\QueueManager\Queue\DbQueue;
use Hector\Connection\Connection;

$dbConnection = new Connection('mysql://localhost:3306');
$queue = new DbQueue(
    connection: $dbConnection, // Database connection
    name: 'default',           // Queue name
    tableName: 'queue_jobs',   // Name of MySQL table
    maxAttempts: 5,            // Maximum attempts of a job
);

use Berlioz\QueueManager\Queue\MemoryQueue;

$queue = new MemoryQueue(
    name: 'default', // Queue name
    retryTime: 30,   // Time to wait after failed job
);

use Aws\Sqs\SqsClient;
use Berlioz\QueueManager\Queue\AwsSqsQueue;

$queue = new AwsSqsQueue(
    sqsClient: new SqsClient(...), // Database connection
    name: 'default',               // Queue name
    queueUrl: '...',               // AWS queue URL
);