PHP code example of zotlo / phalcon-queue

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

    

zotlo / phalcon-queue example snippets


$di->register(new Phalcon\Queue\ServiceProvider());

$di->setShared('config', function () {
    return new \Phalcon\Config\Config([
        'queues'   => [
            'adapter'     => 'mysql',    # mysql, redis, sqlite
            'dbIndex'     => 1,          # Redis database index (only redis)
            'supervisors' => [
                [
                    'queue'           => 'default', # Queue Name
                    'balance'         => 'auto',    # Balance Strategy (auto, simple)
                    'processes'       => 5,         # Maximum Process
                    'tries'           => 0,         # Job Maximum Tries (0 = unlimited)
                    'timeout'         => 90,        # Job Timeout (seconds)
                    'balanceMaxShift' => 5,         # Max processes to start/stop per scaling cycle
                    'balanceCooldown' => 3,         # Seconds between scaling checks
                    'debug'           => false      # Worker debug logging
                ],
                [
                    'queue'           => 'another-queue',
                    'balance'         => 'simple',
                    'processes'       => 5,
                    'tries'           => 0,
                    'timeout'         => 90,
                    'balanceMaxShift' => 5,
                    'balanceCooldown' => 3,
                    'debug'           => false
                ]
            ]
        ]
    ]);
});



namespace App\Jobs;

use Phalcon\Queue\Jobs\Job;

class MyJob extends Job
{
    public function handle(): void
    {
        // your code
    }
}

dispatch(new MyJob());

dispatch(new MyJob())
    ->queue('default');

dispatch(new MyJob())
    ->queue('default')
    ->delay(10); # Delay TTL (seconds)

$jobArray = [
    new MyJob(),
    new MyJob(),
    ...
];

dispatchBatch($jobArray);

# Also, you can set queue with batch.
dispatchBatch($jobArray)
    ->queue('default');

async(function () {
    ...
});

# You can use the 'use' statement.
$uniqId = uniqid();

async(function () use ($uniqId) {
    $taskId = $uniqId;
    ...
});

$job = async(function () {
    ...
});

// Your app codes

// Waits until the job succeeds or fails.
$status = await($job); // Status::COMPLETED or Status::FAILED

// If you want to manage all states yourself, pass 'manageable' as true;
// pending/processing states are then returned immediately instead of blocking.
$status = await($job, true); // Status::PENDING, PROCESSING, FAILED or COMPLETED

$variable = "initial";

async(function () use (&$variable) {
    $variable = "changed";
});

echo $variable; # prints "initial"

use Phalcon\Queue\Channel;

$ch = Channel::make();

$token = uniqid();

async(function () use ($token, $ch) {
    // heavy work...
    sleep(rand(2, 10));

    $ch->write(json_encode(['status' => true, 'msg' => 'message received!', 'id' => $token]));
});

// Blocks until a message arrives (or the timeout expires).
$channelData = $ch->read();

echo $channelData; # {"status":true,"msg":"message received!","id":"..."}

$ch = Channel::make();          # create a single channel
$channels = Channel::makes(5);  # create multiple channels at once

$ch->write(string $message): bool;          # write a message (max 128 KB)
$ch->read(int $timeout = 15): ?string;      # read one message; null if none arrives within $timeout seconds
$ch->readAll(int $timeout = 15): array;     # collect all messages arriving within $timeout seconds

$ch = Channel::make();

for ($i = 0; $i < 3; $i++) {
    async(function () use ($ch, $i) {
        $ch->write("job {$i} done");
    });
}

$messages = $ch->readAll(30); # ["job 0 done", "job 1 done", "job 2 done"]

$console = new Symfony\Component\Console\Application('Phalcon Queue Management', '1.0.0');

$console->addCommands([
    (new \Phalcon\Queue\Commands\ListFailedJobCommand())->setDi($di),
    (new \Phalcon\Queue\Commands\RetryFailedJobCommand())->setDi($di),
    (new \Phalcon\Queue\Commands\RestartQueueCommand())->setDi($di),
    (new \Phalcon\Queue\Commands\ForceStopQueueCommand())->setDi($di),
]);

$console->run();

php cli.php Queue run default

[program:phalcon-queue]
process_name = phalcon-queue
command = /usr/bin/php PHALCON_CLI_PATH/cli.php Queue run default
autostart = true
autorestart = true
user = root
stopsignal = SIGTERM
stopwaitsecs = 30
startretries = 3

[program:phalcon-queue-another]
process_name = another-queue
command = /usr/bin/php PHALCON_CLI_PATH/cli.php Queue run another-queue
autostart = true
autorestart = true
user = root
stopsignal = SIGTERM
stopwaitsecs = 30
startretries = 3