drlenux / workers-run
php, worker, pcntl, messenger
2.0.0.1
2019-10-15 15:04 UTC
Requires
- php: ^7.1
- ext-json: *
- ext-yaml: *
- alecrabbit/php-console-spinner: ^0.52.0
- misterion/ko-process: ^0.5.3
- symfony/lock: ^4.3
- symfony/var-dumper: ^4.3
Suggests
- ext-pcntl: *
- ext-posix: *
- ext-proctitle: *
- ext-sysvmsg: *
- ext-sysvsem: Required for using the Semaphore class
- ext-sysvshm: Required for using the SharedMemory class
README
EXAMPLE
config.php
<?php use DrLenux\WorkersRun\messenger\SemaphoreDb; use DrLenux\WorkersRun\messenger\config\SemaphoreDbConfig; use DrLenux\WorkersRun\lock\SemaphoreLock; return [ 'messenger' => [ 'lockStore' => SemaphoreLock::getStore(), 'db' => [ 'class' => SemaphoreDb::class, 'config' => new SemaphoreDbConfig(123, 500), ] ] ];
Work.php
<?php namespace example; use DrLenux\WorkersRun\Messenger; use DrLenux\WorkersRun\IWork; use DrLenux\WorkersRun\MessengerResponse; /** * Class Work * @package example */ class Work implements IWork { const U_SLEEP = 1000000; /** * @var float|int */ private $time = 0; /** * @var string */ private $message = ''; /** * Work constructor. * @param float $time * @param string $message */ public function __construct(float $time, string $message) { $this->time = $time; $this->message = $message; } /** * @param Messenger $messenger * @return MessengerResponse|null */ public function run(Messenger $messenger): ?MessengerResponse { usleep($this->time * self::U_SLEEP); return (new MessengerResponse(WorkMessageEcho::class, getmypid(), $this->message)); } }
WorkMessageEcho.php
<?php namespace example; use DrLenux\WorkersRun\Messenger; use DrLenux\WorkersRun\IWork; use DrLenux\WorkersRun\MessengerResponse; /** * Class WorkMessageEcho * @package example */ class WorkMessageEcho implements IWork { /** * @param Messenger $messenger * @return MessengerResponse|null * @throws \Exception */ public function run(Messenger $messenger): ?MessengerResponse { $count = 0; $maxCount = 5; while (true) { if ($count++ >= $maxCount) { break; } $res = $messenger->read(__CLASS__); if (count($res)) { foreach ($res as $item) { /** @var MessengerResponse $item */ echo $item->getMessage(); } $count = 0; } usleep(250000); } return null; } }
run.php
<?php require __DIR__ . '/../vendor/autoload.php'; use DrLenux\WorkersRun\Works; use example\{Work, WorkMessageEcho}; use DrLenux\WorkersRun\WorksRun; $works = (new Works()) ->add(new WorkMessageEcho()) ->add(new Work(1, 'is ')) ->add(new Work(0, 'Hi, ')) ->add(new Work(0.7, 'what ')) ->add(new Work(2, 'name?')) ->add(new Work(1.5, 'your ')); $config = require __DIR__ . '/config.php'; (new WorksRun($config)) ->run($works) ->wait();