V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Misakas
V2EX  ›  问与答

关于 fsnotify 在监听文件的写入事件时,消息不即时这件事

  •  
  •   Misakas · Apr 15, 2021 · 1597 views
    This topic created in 1837 days ago, the information mentioned may be changed or developed.

    Windows 系统,网易云会将当前播放的音乐写入 history 文件,用 golang 的 fsnotify 监视文件时事件会延迟个两三秒才到

    用了下面的步骤试了一下,问题应该是在 fsnotify (或者我的代码)上

    • fsnotify 监视文件,用 notepad 更改 -> Write 消息是即时的
    • 网易云切歌,用 notepad 编辑 history 文件 -> notepad 提示已被编辑,消息是即时的
    • fsnotify 监视文件,网易云切歌 -> Write 消息会延迟几秒到

    虽然有点延迟可以接受,但是非常想搞明白原因是什么。希望有人来科普一下或者甩个关键词

    贴个代码,方便大家复现(

    package main
    
    import (
    	"github.com/fsnotify/fsnotify"
    	"os"
    )
    
    func main() {
    	watcher, _ := fsnotify.NewWatcher()
    
    	defer watcher.Close()
    
    	_ = watcher.Add()
    	
    	for {
    		select {
    		case event, ok := <-watcher.Events:
    			if !ok {
    				return
    			}
    			fmt.Println(event)
    		case err, ok := <-watcher.Errors:
    			if !ok {
    				return
    			}
    			fmt.Println("error:", err)
    		}
    	}
    
    	for{
    		//runtime.Gosched()
    		time.Sleep(1* time.Second)
    	}
    }
    
    
    2 replies    2021-04-15 21:26:01 +08:00
    justseemore
        1
    justseemore  
       Apr 15, 2021
    _ = watcher.Add() 这是监测了所有了吧?
    Misakas
        2
    Misakas  
    OP
       Apr 15, 2021
    @zpfhbyx 发帖时不小心修改错了了,watcher.Add() 其实是有值的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   947 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 22:40 · PVG 06:40 · LAX 15:40 · JFK 18:40
    ♥ Do have faith in what you're doing.