Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hotfolder in Go / wait for file to be written

Tags:

go

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 := <-watcher.Event:
        log.Println("event:", ev)
    case err := <-watcher.Error:
        log.Println("error:", err)
    }
}

Any idea / advise?

like image 512
topskip Avatar asked Nov 17 '12 20:11

topskip


1 Answers

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 := <-watcher.Event:
        log.Println("event:", ev)
    case err := <-watcher.Error:
        log.Println("error:", err)
    case <-timer.C:
        f()
    }

    timer.Stop()
}
like image 76
Stephen Weinberg Avatar answered Oct 04 '22 19:10

Stephen Weinberg