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

lxping

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;
            }
        }
    }
}
3965 4 0
4个评论

朕震惊了

太感谢了,正需要呢就来了

  • 暂无评论
walkor

很有用的分享,非常感谢

  • 暂无评论
天道酬勤

学习了

  • 暂无评论
walkor

从webman 1.2.3 版本开始支持支持windows下热更新了。windows下的启动方式为双击 windows.bat.

  • theonewu 2022-04-17

    刚想问,就看到boss的回答了。

年代过于久远,无法发表评论

lxping

633
积分
0
获赞数
0
粉丝数
2019-12-27 加入
🔝