我不知道其他人是怎么做的,但我总是使用supervisor 来处理这些类型的工作。它类似于 cron,但有更多的配置选项。
无论如何,安装示例(CentOS)和实现:
创建一个服务文件,并用这些行填充它:
[Unit]
Description=Process Monitoring and Control Daemon
After=rc-local.service nss-user-lookup.target
[Service]
Type=forking
ExecStart=/usr/bin/supervisord -c /etc/supervisord.conf
[Install]
WantedBy=multi-user.target
然后启用自动启动:
sudo systemctl enable supervisord
并启动服务:
sudo systemctl start supervisord
[注意]
您必须先启动 supervisord,然后才能访问 supervisorctl。
sudo supervisord -c /etc/supervisord.conf
sudo supervisorctl -c /etc/supervisord.conf
这点之后你就可以轻松使用了:
// Reload the daemon’s configuration files, without add/remove (no restarts)
sudo supervisorctl reread
// Reload config and add/remove as necessary, and will restart affected programs
sudo supervisorctl update
sudo supervisorctl <start/restart/stop> <workerIniFileName>:*
[注意]
ini文件位置:/etc/supervisor.d/
示例:random-worker.ini
[program:random-worker]
process_name=%(program_name)s_%(process_num)02d
command=<php/sh/py/command/ect script location> // example: php /var/www/html/project/asd.php
autostart=true
autorestart=true
user=apache // or any other user
numprocs=4 // number of process you would like to execute simultaneously
redirect_stderr=true
stdout_logfile=/var/log/<name of the logfile>.log
脚本实现完全取决于您。 php中的示例:
public function onShutdown()
{
$this->info('Shutdown called, exiting.');
}
public function onSignal($signo)
{
$this->info("Received PCNTL signal {$signo}");
die();
}
public function actionRunWorker($priorityLevel = false)
{
set_time_limit(0);
declare(ticks=1);
register_shutdown_function([$this, 'onShutdown']);
pcntl_signal(SIGTERM, [$this, 'onSignal']);
pcntl_signal(SIGHUP, [$this, 'onSignal']);
pcntl_signal(SIGINT, [$this, 'onSignal']);
sleep(self::WORKER_SLEEP_TIME);
while (1) {
// Your code comes here
sleep(self::WORKER_SLEEP_TIME);
}
}