让windows开发支持代码热更新,workerman-filemonitor for windows

workerman-filemonitor只能用于linux,但是我们平时开发都是用的windows。基于workerman-filemonitor二次修改,可完美实现windwos开发时的代码热更新。


经过测试,windows下不能直接在filemonitor启动的进程中获取我们需要的父进程,所以需要在你启动的gateway文件中添加如下代码(该代码一定要放在Worker::runAll()之前)


require_once __DIR__ . '/FileMonitor.php';
new FileMonitor($web, 'www', 5);

FileMonitor.php


<?php

use \Workerman\Worker;
use \Workerman\Lib\Timer;

/**
* workerman-filemonitor for windows
*
* 监控文件更新并自动reload workerman
*
* 使用方法:
* require_once __DIR__ . '/FileMonitor.php';
* new FileMonitor($worker, $dir, $timer);
*/
class FileMonitor
{
//待监听的项目目录
private $_monitor_dir = '';

//热更新间隔时间,默认3s
private $_interval = 0;

//最后一次同步时间
private $_last_time = 0;

function __construct ($worker, $dir, $timer = 3)
{
// watch Applications catalogue
$this->_monitor_dir = __DIR__ .'/'. $dir;

$this->_interval = $timer;

$this->_last_time = time();

// Emitted when data received
$worker->reloadable = false;

// Emitted when data received
$worker->onWorkerStart = function()
{
// watch files only in daemon mode
if (Worker::$daemonize === false)
{
// chek mtime of files per second
Timer::add($this->_interval, [$this, 'monitor']);
}
};
}

//监听器,kill进程
public function monitor ()
{
// recursive traversal directory
$iterator = new RecursiveDirectoryIterator($this->_monitor_dir);
$iterator = new RecursiveIteratorIterator($iterator);

foreach ($iterator as $file)
{
// only check php files
if (pathinfo($file, PATHINFO_EXTENSION) != 'php') continue;

// check mtime
if ($this->_last_time < $file->getMTime())
{
exec('taskkill -f -pid '. getmypid());
$this->_last_time = $file->getMTime();
return true;
}
}
}
}

3 个评论

太感谢了,正需要呢就来了
很有用的分享,非常感谢
学习了

要回复文章请先登录注册