-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.go
83 lines (73 loc) · 1.07 KB
/
timer.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
82
83
package resourcepool
import (
"sync"
"time"
)
type timerAction = int
const (
stopMsg = iota
resetMsg
triggerMsg
)
type Timer struct {
interval AtomicDuration
mu sync.Mutex
msg chan timerAction
running bool
}
func NewTimer(interval time.Duration) *Timer {
t := Timer{
msg: make(chan timerAction),
}
t.interval.Set(interval)
return &t
}
func(t *Timer) Start(f func()) {
t.mu.Lock()
defer t.mu.Unlock()
if t.running {
return
}
t.running = true
go t.Run(f)
}
func(t *Timer) Run(f func()) {
for {
var ch <-chan time.Time
interval := t.interval.Get()
if interval <= 0 {
ch = nil
} else {
ch = time.After(interval)
}
select {
case msg := <-t.msg:
switch msg {
case stopMsg:
return
case resetMsg:
continue
}
case <-ch:
}
f()
}
}
func(t *Timer) Stop() {
t.mu.Lock()
defer t.mu.Unlock()
if t.running {
t.msg <- stopMsg
t.running = false
}
}
func (t *Timer) Trigger() {
t.mu.Lock()
defer t.mu.Unlock()
if t.running {
t.msg <- triggerMsg
}
}
func (t *Timer) Interval() time.Duration {
return t.interval.Get()
}