-
Notifications
You must be signed in to change notification settings - Fork 1
/
timer.go
160 lines (128 loc) · 2.48 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
package time
import (
"sync"
"time"
)
// reference: [GO语言提前取消定时器](https://blog.csdn.net/u012265809/article/details/114939168)
// TimeoutCallback 表示超时时的回调函数
type TimeoutCallback func()
// Timer is re-packaged time.Timer object, but have different methods.
type Timer interface {
// Run starts timer in the background.
Run() error
// Stop stops the timer if it is running.
Stop() error
// Running check whether timer is running.
Running() bool
// Remain returns remaining time in the timer
Remain() time.Duration
// Elapsed returns elapsed time in the timer
Elapsed() time.Duration
}
// tmr is internal implementation of Timer interface
type tmr struct {
rwlock sync.RWMutex
running bool
paused bool
cb TimeoutCallback
duration time.Duration
end time.Time
stop chan struct{}
}
// NewTimer returns a new timer
func NewTimer(d time.Duration, cb TimeoutCallback) Timer {
return newTmr(d, cb)
}
func newTmr(d time.Duration, cb TimeoutCallback) *tmr {
if d < 0 {
d = 0
}
t := &tmr{
rwlock: sync.RWMutex{},
running: false,
paused: false,
cb: cb,
duration: d,
end: time.Time{},
stop: nil,
}
return t
}
func (t *tmr) Run() error {
t.rwlock.Lock()
defer t.rwlock.Unlock()
if t.running {
return ErrTimerIsAlreadyRunning
}
// init parameters
t.running = true
t.stop = make(chan struct{})
t.end = time.Now().Add(t.duration)
timer := time.NewTimer(t.duration)
cleanWithLock := func() {
t.rwlock.Lock()
{
close(t.stop)
timer.Stop()
t.running = false
t.stop = nil
}
t.rwlock.Unlock()
}
// Start timer and listen timeout event
go func() {
select {
case <-timer.C:
cleanWithLock()
if t.cb != nil {
t.cb()
}
return
case <-t.stop:
cleanWithLock()
return
}
}()
return nil
}
func (t *tmr) Stop() error {
t.rwlock.RLock()
defer t.rwlock.RUnlock()
if !t.running {
return ErrTimerIsNotRunning
}
t.stop <- struct{}{}
return nil
}
func (t *tmr) Running() bool {
t.rwlock.RLock()
b := t.running
t.rwlock.RUnlock()
return b
}
func (t *tmr) Remain() time.Duration {
now := time.Now()
t.rwlock.RLock()
defer t.rwlock.RUnlock()
if !t.running {
return t.duration
}
d := t.end.Sub(now)
if d >= 0 {
return d
}
return 0
}
func (t *tmr) Elapsed() time.Duration {
now := time.Now()
t.rwlock.RLock()
defer t.rwlock.RUnlock()
if !t.running {
return 0
}
d := t.end.Sub(now)
if d >= 0 {
return t.duration - d
}
return t.duration
}