diff --git a/notify.go b/notify.go index 49400d0..d52cbfa 100644 --- a/notify.go +++ b/notify.go @@ -31,12 +31,6 @@ type ( Errors() <-chan error Events() <-chan fsnotify.Event } - filewatcher struct { - // force polling instead event watcher - polling bool - // polling interval express in milliseconds - interval time.Duration - } // fsNotifyWatcher wraps the fsnotify package to satisfy the FileNotifier interface fsNotifyWatcher struct { *fsnotify.Watcher @@ -55,24 +49,31 @@ type ( mu sync.Mutex // closed is used to specify when the poller has already closed closed bool + // polling interval + interval time.Duration } ) // NewPollingWatcher returns a poll-based file watcher -func PollingWatcher() FileWatcher { +func PollingWatcher(interval time.Duration) FileWatcher { + if interval == 0 { + interval = 100 * time.Millisecond + } return &filePoller{ - //interval: f.interval * time.Millisecond, - events: make(chan fsnotify.Event), - errors: make(chan error), + interval: interval, + events: make(chan fsnotify.Event), + errors: make(chan error), } } // New tries to use an fs-event watcher, and falls back to the poller if there is an error -func Watcher() (FileWatcher, error) { - if w, err := EventWatcher(); err == nil { - return w, nil +func Watcher(force bool, interval time.Duration) (FileWatcher, error) { + if !force { + if w, err := EventWatcher(); err == nil { + return w, nil + } } - return PollingWatcher(), nil + return PollingWatcher(interval), nil } // NewEventWatcher returns an fs-event based file watcher @@ -222,7 +223,7 @@ func (w *filePoller) sendEvent(e fsnotify.Event, chClose <-chan struct{}) error func (w *filePoller) watch(f *os.File, lastFi os.FileInfo, chClose chan struct{}) { defer f.Close() for { - time.Sleep(200 * time.Millisecond) + time.Sleep(w.interval) select { case <-chClose: logrus.Debugf("watch for %s closed", f.Name()) diff --git a/notify_test.go b/notify_test.go index 98218f0..3767a94 100644 --- a/notify_test.go +++ b/notify_test.go @@ -10,8 +10,12 @@ import ( "time" ) +const ( + interval = 100 * time.Millisecond +) + func TestPoller_AddRemove(t *testing.T) { - w := PollingWatcher() + w := PollingWatcher(interval) if err := w.Add("no-such-file"); err == nil { t.Fatal("should have gotten error when adding a non-existent file") @@ -39,7 +43,7 @@ func TestPoller_Event(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("No chmod on Windows") } - w := PollingWatcher() + w := PollingWatcher(interval) f, err := ioutil.TempFile("", "test-poller") if err != nil { @@ -83,7 +87,7 @@ func TestPoller_Event(t *testing.T) { } func TestPoller_Close(t *testing.T) { - w := PollingWatcher() + w := PollingWatcher(interval) if err := w.Close(); err != nil { t.Fatal(err) }