PHP code example of patchlevel / worker

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

    

patchlevel / worker example snippets




declare(strict_types=1);

namespace App\Console\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(
    'app:worker',
    'do stuff'
)]
final class WorkerCommand extends Command
{
    protected function configure(): void
    {
        $this
            ->addOption(
                'run-limit',
                null,
                InputOption::VALUE_OPTIONAL,
                'The maximum number of runs this command should execute',
                1
            )
            ->addOption(
                'memory-limit',
                null,
                InputOption::VALUE_REQUIRED,
                'How much memory consumption should the worker be terminated (500MB, 1GB, etc.)'
            )
            ->addOption(
                'time-limit',
                null,
                InputOption::VALUE_REQUIRED,
                'What is the maximum time the worker can run in seconds'
            )
            ->addOption(
                'sleep',
                null,
                InputOption::VALUE_REQUIRED,
                'How much time should elapse before the next job is executed in milliseconds',
                1000
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $logger = new ConsoleLogger($output);
        
        $worker = DefaultWorker::create(
            function ($stop): void {
                // do something
                
                if (/* some condition */) {
                    $stop();
                }
            },
            [
                'runLimit' => $input->getOption('run-limit'),
                'memoryLimit' => $input->getOption('memory-limit'),
                'timeLimit' => $input->getOption('time-limit'),
            ],
            $logger
        );

        $worker->run($input->getOption('sleep') ?: null);

        return 0;
    }
}