任务调度

启动流程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
1. 运行命令 php TaskScheduling.php start -d
2. 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 循环检查是否有未处理的信号
停止流程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
1. 运行命令 php TaskScheduling.php stop
2. 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 Class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

class 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 Class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557

class 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);
}
}
DEMO
1
2
3
4
5
6
7
8
9
10
11
<?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();
0%