inpassor / yii2-daemon
为Yii 2框架提供的简单守护进程扩展
0.3.4
2018-11-19 12:10 UTC
Requires
- yiisoft/yii2: *
README
作者: Inpassor inpassor@yandex.com
GitHub仓库: https://github.com/Inpassor/yii2-daemon
该守护进程是Yii2的控制台应用程序,实现PHP的多任务进程。启动后,它保持在内存中并启动工作进程。每个工作进程可以同时运行的最大进程数是单独设置的。在工作进程中,您可以访问任何Yii2资源。
请注意,为了守护进程的正常运行,您需要PHP扩展pcntl和posix。如果守护进程在Windows系统上运行,则不可用。此外,守护进程的主进程将保留在控制台,直到被中断(Ctrl-C)。
安装
- 使用composer将包添加到您的项目中
composer require inpassor/yii2-daemon
- 将守护进程命令添加到控制台配置文件中的"controllerMap"部分
'controllerMap' => [
...
'daemon' => [
'class' => 'inpassor\daemon\Controller',
'uid' => 'daemon', // The daemon UID. Giving daemons different UIDs makes possible to run several daemons.
'pidDir' => '@runtime/daemon', // PID file directory.
'logsDir' => '@runtime/logs', // Log files directory.
'clearLogs' => false, // Clear log files on start.
'workersMap' => [
'watcher' => [
'class' => 'inpassor\daemon\workers\Watcher',
'active' => true, // If set to false, worker is disabled.
'maxProcesses' => 1, // The number of maximum processes of the daemon worker running at once.
'delay' => 60, // The time, in seconds, the timer should delay in between executions of the daemon worker.
],
...
],
],
],
守护进程的工作进程应在"workersMap"部分列出。参数"class"是唯一必需的。可以设置工作进程配置如下
'workersMap' => [
'watcher' => 'inpassor\daemon\workers\Watcher',
...
],
在这种情况下,所有参数都将从工作进程类中获取。
请注意,守护进程"workersMap"配置部分中定义的工作进程配置变量具有比工作进程类的相应属性更高的优先级。
该守护进程包含名为"inpassor\daemon\workers\Watcher"的工作进程。此工作进程每分钟运行一次,检查守护进程的工作进程是否存活,并从内存中删除已死亡的工作进程。这不是必需的。
- 创建守护进程的工作进程。所有工作进程类都应扩展inpassor\daemon\Worker
class MyWorker extends \inpassor\daemon\Worker
{
public $active = true;
public $maxProcesses = 1;
public $delay = 60;
public function run()
{
$this->log('I live... again!');
// The daemon worker's job goes here.
}
}
工作进程的公共方法run()应在派生类中重写。不要忘记将您的工怍进程添加到守护进程配置中的"workersMap"部分。
在Ubuntu / Debian上作为系统服务运行
-
确保在您的项目目录中有控制台应用程序"yii"。检查"yii"文件是否可执行。
-
检查"vendor/inpassor/yii2-daemon/yiid"文件是否可执行。
-
在root控制台运行
ln -s /path_to_your_project/vendor/inpassor/yii2-daemon/yiid /etc/init.d/yiid
- 创建文件/lib/systemd/system/yiid.service
[Unit]
Description=yiid
[Service]
User=www-data
PIDFile=/path_to_your_project/runtime/daemon/daemon.pid
Type=forking
KillMode=process
ExecStart=/path_to_your_project/vendor/inpassor/yii2-daemon/yiid start
ExecStop=/path_to_your_project/vendor/inpassor/yii2-daemon/yiid stop
[Install]
WantedBy=multi-user.target
- 在root控制台运行
systemctl enable yiid.service
service yiid start