-
Notifications
You must be signed in to change notification settings - Fork 1
/
timer.go
60 lines (50 loc) · 1.02 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
package main
import (
"sync/atomic"
"time"
)
type ResetableTimerStatus uint8
const (
RTCancel ResetableTimerStatus = 0
RTTimeout ResetableTimerStatus = 1
)
type ResetableTimer struct {
resetCh chan bool
cancelCh chan bool
cancelCount int32
duration time.Duration
Status chan ResetableTimerStatus
}
func (r *ResetableTimer) Cancel() {
if atomic.CompareAndSwapInt32(&r.cancelCount, 0, 1) {
select {
case r.cancelCh <- true:
default:
}
}
}
func (r *ResetableTimer) Reset() {
r.resetCh <- true
}
func (r *ResetableTimer) Start() {
atomic.StoreInt32(&r.cancelCount, 0)
select {
case <-r.cancelCh:
r.Status <- RTCancel
case <-time.After(r.duration):
r.Status <- RTTimeout
case <-r.resetCh:
go r.Start()
}
}
func NewResetableTimer(duration time.Duration) *ResetableTimer {
r := &ResetableTimer{
duration: duration,
cancelCount: 0,
resetCh: make(chan bool, 1),
cancelCh: make(chan bool, 1),
Status: make(chan ResetableTimerStatus, 1),
}
go r.Start()
return r
}