Added batching behavior for page building.

Quite often file watcher gets many changes and each change triggered a
build. One build per second should be sufficient. Also added tracking for
new folders.
This commit is contained in:
Egon Elbre 2013-12-15 17:19:22 +02:00 committed by spf13
parent 1979f7d9c7
commit 8d80f9b39e
2 changed files with 103 additions and 31 deletions

56
watcher/batcher.go Normal file
View file

@ -0,0 +1,56 @@
package watcher
import (
"github.com/howeyc/fsnotify"
"time"
)
type Batcher struct {
*fsnotify.Watcher
interval time.Duration
done chan struct{}
Event chan []*fsnotify.FileEvent // Events are returned on this channel
}
func New(interval time.Duration) (*Batcher, error) {
watcher, err := fsnotify.NewWatcher()
batcher := &Batcher{}
batcher.Watcher = watcher
batcher.interval = interval
batcher.done = make(chan struct{}, 1)
batcher.Event = make(chan []*fsnotify.FileEvent, 1)
if err == nil {
go batcher.run()
}
return batcher, err
}
func (b *Batcher) run() {
tick := time.Tick(b.interval)
evs := make([]*fsnotify.FileEvent, 0)
OuterLoop:
for {
select {
case ev := <-b.Watcher.Event:
evs = append(evs, ev)
case <-tick:
if len(evs) == 0 {
continue
}
b.Event <- evs
evs = make([]*fsnotify.FileEvent, 0)
case <-b.done:
break OuterLoop
}
}
close(b.done)
}
func (b *Batcher) Close() {
b.done <- struct{}{}
b.Watcher.Close()
}