PHP code example of mix / worker-pool

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

    

mix / worker-pool example snippets


$jobQueue = new Swoole\Coroutine\Channel(200);
$maxWorkers = 100;
$handler = function ($data) {
    // do something
};
$pool = new Mix\WorkerPool\WorkerPool($jobQueue, $maxWorkers, $handler);

go(function () use ($jobQueue, $pool) {
    // 投放任务
    for ($i = 0; $i < 1000; $i++) {
        $jobQueue->push($i);
    }
    // 停止
    $pool->stop();
});

$pool->run(); // 阻塞等待

class FooHandler implements \Mix\WorkerPool\RunInterface
{
    public function do($data): void
    {
        // do something
    }
}
$pool = new Mix\WorkerPool\WorkerPool($jobQueue, $maxWorkers, new FooHandler());

$maxWorkers = 20;
$maxQueue = 10;
$jobQueue = new Swoole\Coroutine\Channel($maxQueue);
$handler = function ($data) {
    // do something
};
$pool = new Mix\WorkerPool\WorkerPool($jobQueue, $maxWorkers, $handler);

$quit = new Swoole\Coroutine\Channel();
foreach ([SIGHUP, SIGINT, SIGTERM] as $signal) {
    Swoole\Process::signal($signal, function () use ($quit) {
        $quit->push(true);
    });
}

go(function () use ($jobQueue, $pool, $quit) {
    // 投放任务
    while (true) {
        if (!$quit->isEmpty()) {
            $pool->stop();
            return;
        }
        try {
            $data = $redis->brPop(['test'], 1);
        } catch (\Throwable $ex) {
            // print log
            $pool->stop();
            return;
        }
        if (!$data) {
            continue;
        }
        $data = array_pop($data); // brPop命令最后一个键才是值
        $jobQueue->push($data);
    }
});

$pool->run(); // 阻塞等待

class FooHandler implements \Mix\WorkerPool\RunInterface
{
    public function do($data): void
    {
        try {
            // do something
        } catch (\Throwable $ex){
            // print log
        }
    }
}