From dfe0ea8ba56b27cddbed3bf84519df0b3a96a096 Mon Sep 17 00:00:00 2001 From: Sridhar Ratnakumar Date: Fri, 12 Oct 2012 18:12:49 -0700 Subject: [PATCH] optimize polling watcher using stat check does not send 'changed' events if the last modified time hasn't changed. --- watch.go | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/watch.go b/watch.go index 57bd609..dea369d 100644 --- a/watch.go +++ b/watch.go @@ -107,15 +107,33 @@ func (fw *PollingFileWatcher) ChangeEvents() chan bool { stop := make(chan bool) every2Seconds := time.Tick(2 * time.Second) + var prevModTime time.Time go func() { for { - time.Sleep(250 * time.Millisecond) select { - case ch <- true: case <-stop: return default: } + + time.Sleep(250 * time.Millisecond) + fi, err := os.Stat(fw.Filename) + if err != nil { + if os.IsNotExist(err) { + // below goroutine (every2Seconds) will catch up eventually and stop us. + continue + } + panic(err) + } + + modTime := fi.ModTime() + if modTime != prevModTime { + prevModTime = modTime + select { + case ch <- true: + default: + } + } } }() @@ -123,7 +141,7 @@ func (fw *PollingFileWatcher) ChangeEvents() chan bool { for { select { case <-every2Seconds: - // NOTE: not using file descriptor. + // XXX: not using file descriptor as per contract. if _, err := os.Stat(fw.Filename); os.IsNotExist(err) { stop <- true close(ch)