任务调度 发表于 2018-12-31 | 分类于 WorkerMan 启动流程12345678910111213141516171819202122231. 运行命令 php TaskScheduling.php start -d2. checkEnv 检测运行环境 3. init 初始化 3.1 定义保存主进程ID的文件(pidFile) 3.2 生成日志文件(logFile) 3.3 设置主进程标题 3.4 定时器初始化4. parseCommand 解析命令 4.1 检查命令是否正确 4.2 检测主进程是否存在,避免重复运行5. daemonize 以守护进程模式运行,即后台运行6. installSignal 安装信号7. saveMasterPid 保存主进程ID到文件(pidFile)8. forkProcess 循环创建子进程,到这一步后,主进程和子进程开始执行各自的逻辑 8.1 主进程 8.1.1 保存创建的子进程ID(childPidMap) 8.1.2 resetStd 关闭标准输出 8.1.3 monitorProcess 监控进程 8.1.3.1 监控子进程退出(异常退出时记录日志并重新启动) 8.1.3.2 监控主进程退出(前提是子进程已全部退出) 8.2 子进程 8.2.1 执行回调函数 onStart 8.2.2 循环检查是否有未处理的信号 停止流程12345678910111213141516171819202122231. 运行命令 php TaskScheduling.php stop2. checkEnv 检测运行环境 3. init 初始化 3.1 定义保存主进程ID的文件(pidFile) 3.2 生成日志文件(logFile) 3.3 设置主进程标题 3.4 定时器初始化4. parseCommand 解析命令 4.1 检查命令是否正确 4.2 检测主进程是否存在,避免重复运行 4.3 发送停止信号给主进程 4.3.1 signalHandler 触发安装信号时的回调函数 4.3.2 stopAll 停止所有进程 4.3.2.1 发送停止信号给所有子进程,到这一步后,主进程和子进程开始执行各自的逻辑 4.3.2.1.1 主进程 I. 如果不是优雅停止,则启用定时器,2秒后杀死子进程 II. 每隔1秒检测子进程是否被杀死,若已被杀死,则释放childPidMap对应的pid III. monitorProcess 监听到子进程退出,则释放childPidMap对应的pid,当子进程全部退出后,则退出主进程,并删除主进程PID的保存文件 4.3.2.1.2 子进程 I. signalHandler 触发安装信号时的回调函数 II. stopAll 停止所有进程 III. 执行回调函数 onStop IV. 退出子进程 Timer Class123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475class Timer{ /** * Tasks that based on ALARM signal. * * @var array */ private static $tasks = []; /** * Init. */ public static function init() { // Install a signal processor pcntl_signal(SIGALRM, ['Timer', 'signalHandler'], false); } /** * ALARM signal handler. */ public static function signalHandler() { pcntl_alarm(1); self::tick(); } /** * Add task. * * @param float $timeInterval * @param callable $func * @param bool $persistent */ public static function add($timeInterval, $func, $persistent = true) { if (empty(self::$tasks)) { pcntl_alarm(1); } $nowTime = time(); $runTime = $nowTime + $timeInterval; if (!isset(self::$tasks[$runTime])) { self::$tasks[$runTime] = []; } self::$tasks[$runTime][] = [$timeInterval, $func, $persistent]; } /** * Tick. */ public static function tick() { if (empty(self::$tasks)) { pcntl_alarm(0); return; } $nowTime = time(); foreach (self::$tasks as $runTime => $taskData) { if ($nowTime >= $runTime) { foreach ($taskData as $index => $task) { call_user_func_array($task[1], []); if ($task[2]) { self::add($task[0], $task[1], $task[2]); } } unset(self::$tasks[$runTime]); } } }} TaskScheduling Class123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557class TaskScheduling{ /** * Status starting. * * @var int */ const STATUS_STARTING = 1; /** * Status running. * * @var int */ const STATUS_RUNNING = 2; /** * Status shutdown. * * @var int */ const STATUS_SHUTDOWN = 3; /** * Number of processes. * * @var int */ public $count = 1; /** * Log file. * * @var string */ public $logFile = ''; /** * The file to store master process PID. * * @var string */ public $pidFile = ''; /** * Emitted when processes start. * * @var callback */ public $onStart = null; /** * Emitted when processes stoped. * * @var callback */ public $onStop = null; /** * Start file. * * @var string */ protected $startFile = ''; /** * Daemonize mode. * * @var bool */ protected $daemonizeMode = false; /** * Graceful stop or not. * * @var string */ protected $gracefulStop = false; /** * The PID of master process. * * @var int */ protected $masterPid = 0; /** * The PID Map of child process. * * @var array */ protected $childPidMap = []; /** * Current status. * * @var int */ protected $status; /** * Constructor. * * @throws Exception */ public function __construct() { } /** * Run all. * * @throws Exception */ public function runAll() { $this->checkEnv(); $this->init(); $this->parseCommand(); $this->daemonize(); $this->installSignal(); $this->saveMasterPid(); $this->forkProcess(); $this->resetStd(); $this->monitorProcess(); } /** * Check env. */ protected function checkEnv() { // Only for cli if (php_sapi_name() != 'cli') { exit("only run in command line mode \n"); } // Only for linux if (strpos(strtolower(PHP_OS), 'win') === 0) { exit("Not support windows\n"); } // Need pcntl extension if (!extension_loaded('pcntl')) { exit("Please install pcntl extension."); } // Need posix extension if (!extension_loaded('posix')) { exit("Please install posix extension."); } } /** * Init. */ protected function init() { $backtrace = debug_backtrace(); $this->startFile = $backtrace[count($backtrace) - 1]['file']; if (empty($this->pidFile)) { $this->pidFile = __DIR__ . '/' . str_replace('/', '_', $this->startFile) . '.pid'; } if (empty($this->logFile)) { $this->logFile = __DIR__ . '/' . static::class . '.log'; } $this->logFile = (string)$this->logFile; if (!is_file($this->logFile)) { touch($this->logFile); chmod($this->logFile, 0622); } $this->status = static::STATUS_STARTING; $this->setProcessTitle('master process start_file=' . $this->startFile); Timer::init(); } /** * Parse command. */ protected function parseCommand() { global $argv; $availableCommands = [ 'start', 'stop', ]; $usage = "<y>Usage: </y>\n php yourfile <command> [mode]\n<y>Available commands:</y>\n <g>start</g>\t\tStart task in DEBUG mode. [Use mode -d to start in DAEMON mode]\n <g>stop</g>\t\tStop task.\n"; if (!isset($argv[1]) || !in_array($argv[1], $availableCommands)) { if (isset($argv[1])) { static::output("Unknown command: {$argv[1]}\n"); } } $command = trim($argv[1]); $mode = $argv[2] ?? ''; // Start command. if ($command === 'start') { if ($mode === '-d' || $this->daemonizeMode) { $modeDesc = ' in DAEMON mode.'; } else { $modeDesc = ' in DEBUG mode.'; } $this->log($command . $modeDesc); } // Avoid repeated run $masterPid = is_file($this->pidFile) ? file_get_contents($this->pidFile) : 0; $masterIsAlive = $masterPid && posix_kill($masterPid, 0) && posix_getpid() != $masterPid; if ($masterIsAlive && $command === 'start') { $this->log('already running', $masterPid); exit; } switch ($command) { case 'start': if ($mode === '-d') { $this->daemonizeMode = true; } break; case 'stop': if ($mode === '-g') { $this->gracefulStop = true; $sig = SIGTERM; $this->log('process is gracefully stopping ...'); } else { $this->gracefulStop = false; $sig = SIGINT; $this->log('process is stopping ...'); } // Send stop signal to master process. $masterPid && posix_kill($masterPid, $sig); $timeout = 5; $startTime = time(); // Check master process is still alive? while (1) { $masterIsAlive = $masterPid && posix_kill($masterPid, 0); if ($masterIsAlive) { if (!$this->gracefulStop && time() - $startTime >= $timeout) { $this->log('process stop fail.'); exit; } usleep(10000); continue; } $this->log('process stop success.'); exit(0); } break; default : static::output($usage); exit; } } /** * Run as deamon mode. * * @throws Exception */ protected function daemonize() { if (!$this->daemonizeMode) { return; } $pid = pcntl_fork(); if ($pid === -1) { throw new Exception('fork fail'); } elseif ($pid > 0) { exit(0); } if (posix_setsid() === -1) { throw new Exception('setsid fail'); } // Fork again avoid SVR4 system regain the control of terminal. $pid = pcntl_fork(); if ($pid === -1) { throw new Exception('fork fail'); } elseif ($pid > 0) { exit(0); } umask(0); $this->setProcessTitle(' master process'); } /** * Install signal. */ protected function installSignal() { // stop pcntl_signal(SIGINT, [$this, 'signalHandler'], false); // graceful stop pcntl_signal(SIGTERM, [$this, 'signalHandler'], false); // quit pcntl_signal(SIGQUIT, [$this, 'signalHandler'], false); // ignore pcntl_signal(SIGPIPE, SIG_IGN, false); } /** * Signal handler. * * @param $signal */ protected function signalHandler($signal) { switch ($signal) { case SIGINT: $this->gracefulStop = false; $this->stopAll(); break; case SIGTERM: $this->gracefulStop = true; $this->stopAll(); break; } } /** * Stop all. */ public function stopAll() { $this->status = static::STATUS_SHUTDOWN; // For master process if ($this->masterPid === posix_getpid()) { $this->log('master process stopping ...'); $msg = 'child process is'; if ($this->gracefulStop) { $sig = SIGTERM; $msg .= ' gracefully'; } else { $sig = SIGINT; } $msg .= ' stopping ...'; foreach ($this->childPidMap as $pid) { $this->log($msg, $pid); posix_kill($pid, $sig); if (!$this->gracefulStop) { $instance = $this; Timer::add(2, function () use ($instance, $pid) { posix_kill($pid, SIGKILL); $this->log('child process stopping success.', $pid); }, false); } Timer::add(1, [$this, 'checkIfChildRunning']); } } // For child processes else { $this->log('child process stopping success.'); if ($this->onStop) { try { call_user_func($this->onStop, $this); } catch (Exception $e) { $this->log($e); exit(250); } } exit(0); } } /** * private if child processes is really running */ public function checkIfChildRunning() { foreach ($this->childPidMap as $pid) { if (!posix_kill($pid, 0)) { unset($this->childPidMap[$pid]); } } } /** * Save master pid. * * @throws Exception */ protected function saveMasterPid() { $this->masterPid = posix_getpid(); if (file_put_contents($this->pidFile, $this->masterPid) === false) { throw new Exception('can not save pid to ' . $this->pidFile); } } /** * Fork process. * * @throws Exception */ protected function forkProcess() { while (count($this->childPidMap) < $this->count) { $pid = pcntl_fork(); // For master process if ($pid > 0) { $this->childPidMap[$pid] = $pid; } // For child processes elseif ($pid === 0) { $this->setProcessTitle('child process'); $this->run(); exit(250); } else { throw new Exception('fork fail'); } } } /** * Run. */ protected function run() { try { if ($this->onStart) { call_user_func($this->onStart, $this); } while (1) { // Calls signal handlers for pending signals. pcntl_signal_dispatch(); } } catch (Exception $e) { $this->log($e); // Avoid rapid infinite loop exit. sleep(1); exit(250); } } /** * Reset Std. */ protected function resetStd() { if (!$this->daemonizeMode) { return; } fclose(STDIN); fclose(STDOUT); fclose(STDERR); $stdoutFile = '/dev/null'; fopen($stdoutFile, 'r'); fopen($stdoutFile, 'a'); fopen($stdoutFile, 'a'); } /** * Monitor process. * * @throws Exception */ protected function monitorProcess() { $this->status = static::STATUS_RUNNING; while (1) { pcntl_signal_dispatch(); $status = 0; $pid = pcntl_wait($status, WUNTRACED); pcntl_signal_dispatch(); if ($pid > 0) { if (isset($this->childPidMap)) { if ($status !== 0) { $this->log("child process exit with status {$status}.", $pid); } unset($this->childPidMap[$pid]); } // Is still running state then fork a new worker process. if ($this->status !== static::STATUS_SHUTDOWN) { $this->forkProcess(); } } if ($this->status === static::STATUS_SHUTDOWN && empty($this->childPidMap)) { $this->log('master process stopping success.'); @unlink($this->pidFile); exit(0); } } } /** * Set process title. * * @param string $title */ protected function setProcessTitle(string $title) { if (function_exists('cli_set_process_title')) { cli_set_process_title(static::class . " {$title}"); } } /** * Log. * * @param string $msg * @param int $pid */ protected function log(string $msg, int $pid = 0) { !$pid && ($pid = posix_getpid()); $msg = " [{$this->startFile}] pid:{$pid} {$msg}" . PHP_EOL; if (!$this->daemonizeMode) { static::output($msg); } file_put_contents((string)$this->logFile, date('Y-m-d H:i:s') . ' ' . static::class . $msg, FILE_APPEND | LOCK_EX); } /** * Output. * * @param string $msg */ public static function output(string $msg) { $stream = STDOUT; $line = "\033[1A\n\033[K"; $green = "\033[32;40m"; $yellow = "\033[33;40m"; $end = "\033[0m"; $msg = str_replace(['<n>', '<g>', '<y>'], [$line, $green, $yellow], $msg); $msg = str_replace(['</n>', '</g>', '</y>'], $end, $msg); fwrite($stream, $msg); fflush($stream); }} DEMO1234567891011<?php $task = new TaskScheduling();$task->count = 4;// onStart内的方法会运行$this->count次$task->onStart = function ($task) { echo date('Y-m-d H:i:s') . ' pid:' . posix_getpid() . ' is start.' . PHP_EOL;};$task->onStop = function ($task) { echo date('Y-m-d H:i:s') . ' pid:' . posix_getpid() . ' is exit.' . PHP_EOL;};$task->runAll(); 本文作者:Mr 本文链接: http://sevming.github.io/PHP/task-scheduling.html 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!