izabolotnev / fork-manager
简单的分支管理器
v1.0
2015-10-14 07:20 UTC
Requires
- php: >=5.4
- ext-pcntl: *
This package is auto-updated.
Last update: 2024-09-05 18:24:05 UTC
README
简单的分支管理器。它可以一次性运行任务,也可以反复运行。适用于处理队列和其他计划目的。
需求
- PHP 5.4 或更高版本
- PCNTL 扩展
安装
推荐通过将依赖项添加到您的 composer.json 来安装此库。
{ "require": { "izabolotnev/fork-manager": "~1.0" } }
发布说明
- 1.0.0 (2015-10-14, 首次发布)
- 添加了
ForkManager
类 - 添加了
Task
类
用法
class SampleTask extends \izabolotnev\Task { protected $expectedIterations; protected $remainderIterations; protected $verbose = false; /** * @var bool Switch to true if intercepted SIGTERM */ protected $isStopping = false; /** * @param int $iterations * @param bool $verbose */ public function __construct($iterations, $verbose = false) { $this->expectedIterations = max($iterations, 0); $this->remainderIterations = $this->expectedIterations; $this->verbose = (bool)$verbose; } protected function afterFork() { pcntl_signal(SIGTERM, [$this, 'handlerSigTerm']); // For test purposes call handlerSigTerm after Ctrl+C pcntl_signal(SIGINT, [$this, 'handlerSigTerm']); } /** * Handler for the SIGTERM signal. * Gracefull exit */ public function handlerSigTerm() { $this->remainderIterations = min($this->expectedIterations, 5); $this->isStopping = true; $this->verbose && fputs(\STDOUT, 'Gracefull stop' . PHP_EOL); } /** * Handler for the SIGINT signal/ * Exit immediately */ public function handlerSigInt() { $this->expectedIterations = 0; $this->isStopping = true; $this->beforeExit(); exit(0); } /** * @return int */ public function process() { $date = new \DateTime(); $pid = getmypid(); $this->verbose && fputs(\STDOUT, sprintf('Process #%s' . PHP_EOL, $pid)); $i = 1; while ($this->remainderIterations-- > 0) { $this->verbose && fputs(\STDOUT, sprintf( "Process #%d | %'.03d/%d \033[%sm%s\033[0m" . PHP_EOL, $pid, $i++, $this->expectedIterations, $this->isStopping ? '0;33' : '0;32', $date->modify('+1 second')->format('Y-m-d H:i:s') )); sleep(1); } return 0; } } $task = new SampleTask(100, true); $forkManager = new \izabolotnev\ForkManager($task, 2, [\izabolotnev\ForkManager::DEBUG => true]); $forkManager->once();