-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.go
82 lines (66 loc) · 993 Bytes
/
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
package timer
import (
"sync"
"time"
)
type Timer struct {
tm *time.Timer
mtx *sync.Mutex
ev_ch chan struct{}
running bool
}
func NewTimer() *Timer {
return &Timer{
mtx: &sync.Mutex{},
running: false,
ev_ch: make(chan struct{}, 1),
}
}
func (t *Timer) Recv() <-chan struct{} {
t.mtx.Lock()
defer t.mtx.Unlock()
return t.ev_ch
}
func (t *Timer) on_time() {
t.mtx.Lock()
defer t.mtx.Unlock()
if !t.running {
return
}
select {
case t.ev_ch <- struct{}{}:
default:
}
}
func (t *Timer) Stop() {
t.mtx.Lock()
defer t.mtx.Unlock()
if !t.running {
return
}
t.stop()
}
func (t *Timer) Start(d time.Duration) {
t.mtx.Lock()
defer t.mtx.Unlock()
if t.running {
t.stop()
}
t.start(d)
}
func (t *Timer) stop() {
t.running = false
t.tm.Stop()
select {
case <-t.ev_ch:
default:
}
}
func (t *Timer) start(d time.Duration) {
if t.tm == nil {
t.tm = time.AfterFunc(d, t.on_time)
} else {
t.tm.Reset(d)
}
t.running = true
}