1 Star 0 Fork 0

小鱼儿小董子/dongli-kit

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
fswatch.go 1.74 KB
Copy Edit Raw Blame History
GStones authored 2024-05-09 17:30 +08:00 . 155 fix fix server tls watch (#156)
package tools
import (
"context"
"time"
"go.uber.org/zap"
"gopkg.in/fsnotify.v1"
)
// Watch watches the filesystem path `path`. When anything changes, changes are
// batched for the period `batchFor`, then `processEvent` is called.
//
// Returns a destroy() function to terminate the watch.
func Watch(logger *zap.Logger, path string, batchFor time.Duration, processEvent func()) (func(), error) {
logger = logger.With(zap.String("watch files", path))
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
destroy := func() {
cancel()
_ = watcher.Close()
}
if err := watcher.Add(path); err != nil {
destroy()
return nil, err
}
go batchWatch(ctx, batchFor, watcher.Events, watcher.Errors, processEvent, func(e error) {
logger.Error("watcher error", zap.Error(e))
})
return destroy, nil
}
// batchWatch: watch for events; when an event occurs, keep draining events for duration `batchFor`, then call processEvent().
// Intended for batching of rapid-fire events where we want to process the batch once, like filesystem update notifications.
func batchWatch(
ctx context.Context,
batchFor time.Duration,
events chan fsnotify.Event,
errors chan error,
processEvent func(),
onError func(error),
) {
timer := time.NewTimer(0)
var timerCh <-chan time.Time
for {
select {
// start a timer when an event occurs, otherwise ignore event
case <-events:
if timerCh == nil {
timer.Reset(batchFor)
timerCh = timer.C
}
// on timer, run the batch; nil channels are silently ignored
case <-timerCh:
processEvent()
timerCh = nil
// handle errors
case err := <-errors:
onError(err)
// on cancel, abort
case <-ctx.Done():
return
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wanjimao/dongli-kit.git
git@gitee.com:wanjimao/dongli-kit.git
wanjimao
dongli-kit
dongli-kit
v0.0.37

Search