-
Notifications
You must be signed in to change notification settings - Fork 0
/
notify.go
81 lines (66 loc) · 1.35 KB
/
notify.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package notify
import (
"context"
"fmt"
"sync/atomic"
"time"
"github.com/deweppro/go-app/console"
"github.com/fsnotify/fsnotify"
)
type Notify struct {
watcher *fsnotify.Watcher
handler func(ctx context.Context)
}
func New() (*Notify, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, fmt.Errorf("init watcher: %w", err)
}
return &Notify{
watcher: watcher,
}, nil
}
func (v *Notify) Path(path string) error {
return v.watcher.Add(path)
}
func (v *Notify) Handler(cb func(ctx context.Context)) {
v.handler = cb
}
func (v *Notify) Run(ctx context.Context, ival int64) error {
tick := time.NewTicker(time.Second * time.Duration(ival))
defer tick.Stop()
func() {
var change int32 = 0
ctx0, cncl0 := context.WithCancel(ctx)
go v.handler(ctx0)
for {
select {
case <-tick.C:
if atomic.CompareAndSwapInt32(&change, 1, 0) {
cncl0()
<-ctx0.Done()
ctx0, cncl0 = context.WithCancel(ctx)
go v.handler(ctx0)
}
case <-ctx.Done():
cncl0()
return
case ev, ok := <-v.watcher.Events:
if !ok {
cncl0()
return
}
if ev.Op&fsnotify.Write == fsnotify.Write {
atomic.CompareAndSwapInt32(&change, 0, 1)
}
case ev, ok := <-v.watcher.Errors:
if !ok {
cncl0()
return
}
console.Errorf(ev.Error())
}
}
}()
return v.watcher.Close()
}