// 确认pcntl扩展安装且php.ini中disable_functions中没有pcntl_系列的函数
// $ php -m | grep pcntl
// pcntl
// disable_functions=
需要用到的几个函数:
/**
* Installs a signal handler
* @link https://php.net/manual/en/function.pcntl-signal.php
* @param int $signo <p>
* The signal number.
* </p>
* @param callable|int $handler <p>
* The signal handler. This may be either a callable, which
* will be invoked to handle the signal, or either of the two global
* constants <b>SIG_IGN</b> or <b>SIG_DFL</b>,
* which will ignore the signal or restore the default signal handler
* respectively.
* </p>
* <p>
* If a callable is given, it must implement the following
* signature:
* </p>
* <p>
* void<b>handler</b>
* <b>int<i>signo</i></b>
* <i>signo</i>
* The signal being handled.
* @param bool $restart_syscalls [optional] <p>
* Specifies whether system call restarting should be used when this
* signal arrives.
* </p>
* @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure.
* @since 4.1.0
* @since 5.0
*/
function pcntl_signal ($signo, $handler, $restart_syscalls = true) {}
/**
* Calls signal handlers for pending signals
* @link https://php.net/manual/en/function.pcntl-signal-dispatch.php
* @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure.
* @since 5.3.0
*/
function pcntl_signal_dispatch () {}
/**
* Set an alarm clock for delivery of a signal
* @link https://php.net/manual/en/function.pcntl-alarm.php
* @param int $seconds <p>
* The number of seconds to wait. If <i>seconds</i> is
* zero, no new alarm is created.
* </p>
* @return int the time in seconds that any previously scheduled alarm had
* remaining before it was to be delivered, or 0 if there
* was no previously scheduled alarm.
* @since 4.3.0
* @since 5.0
*/
function pcntl_alarm ($seconds) {}
* index.php
<?php
set_time_limit(0);
ignore_user_abort();
define('TICK_INTERVAL', 2);
// 注册信号处理函数
$tickInt = TICK_INTERVAL;
pcntl_signal(SIGALRM, function() use ($tickInt) {
printf("Time: %s, Func: %s\n",
date("Y-m-d H:i:s", time()), __FUNCTION__);
fflush(STDOUT);
// 再次发送ALARM信号触发执行下次信号处理函数
pcntl_alarm($tickInt);
});
pcntl_signal(SIGINT, function() {
printf("SIGINT caught\n");
exit(0);
});
// 发送ALARM信号启动定时器
pcntl_alarm($tickInt);
printf("Ticker is starting at: %s\n", date("Y-m-d H:i:s"));
// 分发信号
while (1) {
pcntl_signal_dispatch();
sleep(1);
}
$ php index.php
Ticker is starting at: 2019-08-27 09:50:50
Time: 2019-08-27 09:50:52, Func: {closure}
Time: 2019-08-27 09:50:54, Func: {closure}
Time: 2019-08-27 09:50:56, Func: {closure}
^CSIGINT caught
php crontab 解析: https://github.com/jkonieczny/PHP-Crontab/blob/master/Crontab.class.php