enthusiphp监控⽂件夹变化,swoole开发中监听⽬录⽂件变化,⾃动重
启项⽬
在使⽤swoole的项⽬中, 在开发时, 会经常改动代码并查看效果, 由于swoole项⽬是常驻内存的, 代码改动后并不会影响已经在运⾏中并加载过该代码的程序, 所以需要重启项⽬. 为了在改动代码之后可以⾃动重启项⽬, 写了如下脚本(需要inotify拓展)
// watcher.php
// 我这⾥⽤的laravoole开发laravel项⽬,所以只需要reload,并不需要把master进程也重启
new Watcher(__DIR__, function () {
速记符号echo 'modified' . PHP_EOL;
passthru('php artisan laravoole reload');
whatforecho date('H:i:s') . ' 已执⾏ php artisan laravoole reload' . PHP_EOL;
}, ['/storage']);
class Watcher
{
protected $cb; // 回调函数, 重启逻辑在回调⾥⾯定义
protected $modified = fal; // 是否有代码更新
protected $minTime = 2000; // 最⼩触发重启间隔, 防⽌密集更新代码导致频繁重启项⽬
protected $ignored = []; // 忽略的⽬录, ⽤phpstorm开发的话最好把 .idea⽬录加进来, 不然会频繁重启.如果重启有记录⽇志, 把⽇志也加进来, 不然会导致⽆限重启(因为你⼀重启就会检测到⽂件改动, 继续重启)
public function __construct($dir, $cb, $ignore = [])
{
$this->cb = $cb;
foreach ($ignore as $item) {
$this->ignored[] = $dir . $item;
}
$this->watch($dir);
湖南培训
}
protected function watch($directory)
{
//创建⼀个inotify句柄
$fd = inotify_init();
//监听⽂件,仅监听修改操作,如果想要监听所有事件可以使⽤IN_ALL_EVENTS
inotify_add_watch($fd, __DIR__, IN_MODIFY);
foreach ($this->getAllDirs($directory) as $dir) {
inotify_add_watch($fd, $dir, IN_MODIFY);
}回应英语
echo 'watch start' . PHP_EOL;
//加⼊到swoole的事件循环中
深圳城市学院swoole_event_add($fd, function ($fd) {
$events = inotify_read($fd);
if ($events) {
$this->modified = true;
}
});
每 2 秒检测⼀下modified变量是否为真
swoole_timer_tick(2000, function () {
if ($this->modified) {百度字典在线查询
($this->cb)();
操场的英文$this->modified = fal;
六级作文万能句型}
});
}
// 使⽤迭代器遍历⽬录
protected function getAllDirs($ba)
{
$files = scandir($ba);
foreach ($files as $file) {
if ($file == '.' || $file == '..') continue;
推迟英文$filename = $ba . DIRECTORY_SEPARATOR . $file; if (in_array($filename, $this->ignored)) continue;
if (is_dir($filename)) {
yield $filename;
yield from $this->getAllDirs($filename);
}
}
}
}