在Go中的热文件夹/等待文件被写入

huangapple go评论80阅读模式
英文:

Hotfolder in Go / wait for file to be written

问题

我正在尝试在Go中将一个目录设置为热文件夹。一旦文件完成写入该目录,就应该调用一个函数。

现在我遇到了https://github.com/howeyc/fsnotify,它似乎是这样一个热文件夹的好基础。

我的问题是,fsnotify在写入期间会发出许多“文件更改”事件,但在完成时不会发出任何事件,所以我认为这种方式不可能看到进程是否已经完成写入文件。

所以我想到的是“在最后一个'文件更改'事件之后等待一秒钟,然后运行我的函数。但我不确定这是否是处理问题的最佳方法,也不确定如何将其清晰地集成到主事件循环中(来自给定的github页面):

for {
select {
case ev := <-watcher.Event:
log.Println("event:", ev)
case err := <-watcher.Error:
log.Println("error:", err)
}
}

有什么想法/建议吗?

英文:

I am trying to setup a directory as a hotfolder in Go. As soon as a file is finished written to that directory, a function should get called.

Now I came across https://github.com/howeyc/fsnotify that seems to be a good building block for such a hotfolder.

My problem is that fsnotify emits lots of "file changed" events during the write but none when finished, so I assume its not possible that way to see if a process has finished writing files.

So I would think of "wait one second after the last 'file changed' event and then run my function. But I am unsure if this is the best way to deal with the problem and I am not really sure how to integrate this cleanly in the main event loop (from the given github page):

for {
	select {
	case ev := &lt;-watcher.Event:
		log.Println(&quot;event:&quot;, ev)
	case err := &lt;-watcher.Error:
		log.Println(&quot;error:&quot;, err)
	}
}

Any idea / advise?

答案1

得分: 6

以下代码将等待,直到至少一秒钟没有收到任何事件,然后调用f()

for {
    timer := time.NewTimer(1*time.Second)

    select {
    case ev := <-watcher.Event:
        log.Println("事件:", ev)
    case err := <-watcher.Error:
        log.Println("错误:", err)
    case <-timer.C:
        f()
    }

    timer.Stop()
}
英文:

The following code will wait until no event has been received for at least one second and then call f().

for {
    timer := time.NewTimer(1*time.Second)

    select {
    case ev := &lt;-watcher.Event:
        log.Println(&quot;event:&quot;, ev)
    case err := &lt;-watcher.Error:
        log.Println(&quot;error:&quot;, err)
    case &lt;-timer.C:
        f()
    }

    timer.Stop()
}

huangapple
  • 本文由 发表于 2012年11月18日 04:36:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/13434555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定