PHP code example of ttpryg / queue

1. Go to this page and download the library: Download ttpryg/queue 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/ */

    

ttpryg / queue example snippets


namespace App\Jobs;

use Ttpryg\Queue\BaseJob;

class SendEmailJob extends BaseJob
{
    protected int $tries = 3;
    protected int $retryAfter = 60;

    public function process(): void
    {
        $recipient = $this->data['email'] ?? null;
        $subject   = $this->data['subject'] ?? 'Notification';

        // Perform job logic here...
        echo "Sending email to {$recipient} with subject '{$subject}'\n";
    }
}

use PDO;
use Ttpryg\Queue\QueueManager;
use Ttpryg\Queue\Config\QueueConfig;
use Ttpryg\Queue\Database\PdoDatabaseAdapter;
use App\Jobs\SendEmailJob;

// 1. Setup PDO connection
$pdo = new PDO('mysql:host=127.0.0.1;dbname=app_db', 'dbuser', 'dbpass', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

// 2. Setup Configuration
$config = QueueConfig::fromArray([
    'defaultHandler' => 'database',
    'database' => [
        'table' => 'queue_jobs',
    ],
    'jobHandlers' => [
        SendEmailJob::class => SendEmailJob::class,
    ],
]);

// 3. Instantiate Queue Manager
$dbAdapter = new PdoDatabaseAdapter($pdo);
$queueManager = new QueueManager($config, $dbAdapter);

$queue = $queueManager->init();

// 4. Push Job to Queue
$result = $queue->push('emails', SendEmailJob::class, [
    'email'   => '[email protected]',
    'subject' => 'Welcome to our platform!',
]);

if ($result->isSuccess) {
    echo "Job pushed successfully with ID: {$result->jobId}\n";
}

// Dispatch job with 5-minute delay and priority level 10
$queue->delay(300)
      ->priority(10)
      ->push('emails', SendEmailJob::class, ['email' => '[email protected]']);

#!/usr/bin/env php


ponent\Console\Application;
use Ttpryg\Queue\QueueManager;
use Ttpryg\Queue\Config\QueueConfig;
use Ttpryg\Queue\Database\PdoDatabaseAdapter;
use Ttpryg\Queue\Console\Commands\WorkCommand;
use Ttpryg\Queue\Console\Commands\ClearCommand;
use Ttpryg\Queue\Console\Commands\FailedCommand;
use Ttpryg\Queue\Console\Commands\RetryCommand;

$pdo = new PDO('mysql:host=127.0.0.1;dbname=app_db', 'dbuser', 'dbpass');
$config = QueueConfig::fromArray(['defaultHandler' => 'database']);
$queue = (new QueueManager($config, new PdoDatabaseAdapter($pdo)))->init();

$app = new Application('Ttpryg Queue CLI', '1.0.0');
$app->add(new WorkCommand($queue));
$app->add(new ClearCommand($queue));
$app->add(new FailedCommand($queue));
$app->add(new RetryCommand($queue));

$app->run();
bash
php bin/queue queue:work --queue=emails --memory=128 --tries=3