-
Notifications
You must be signed in to change notification settings - Fork 0
/
periodic.go
66 lines (55 loc) · 889 Bytes
/
periodic.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
package health
import (
"sync"
"time"
)
type periodic struct {
fn func() error
d time.Duration
chs map[chan<- error]bool
done chan struct{}
m sync.Mutex
}
func Periodic(fn func() error, d time.Duration) Check {
return &periodic{fn: fn, d: d, chs: map[chan<- error]bool{}}
}
func (p *periodic) Notify(ch chan<- error) {
p.m.Lock()
defer p.m.Unlock()
p.chs[ch] = true
if len(p.chs) > 1 {
return
}
p.done = make(chan struct{})
go func() {
L:
for {
t := time.NewTimer(p.d)
select {
case <-t.C:
case <-p.done:
if !t.Stop() {
<-t.C
}
break L
}
err := p.fn()
p.m.Lock()
for ch := range p.chs {
select {
case ch <- err:
default:
}
}
p.m.Unlock()
}
}()
}
func (p *periodic) Stop(ch chan<- error) {
p.m.Lock()
defer p.m.Unlock()
delete(p.chs, ch)
if len(p.chs) == 0 {
close(p.done)
}
}