-
Notifications
You must be signed in to change notification settings - Fork 22
/
timer.go
124 lines (102 loc) · 2.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
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
package timermanager
import (
"errors"
"sync"
"time"
"github.com/aliyun/aliyun_assist_client/agent/util/wrapgo"
)
type scheduled interface {
nextRun() (time.Duration, error)
}
type TimerCallback func()
type Timer struct {
Schedule scheduled
callback TimerCallback
refreshTimer chan bool
skipWait chan bool
quit chan bool
rwLock sync.RWMutex
isRunning bool
err error
}
var (
ErrNoNextRun = errors.New("Schedule has finished and no next run")
)
func NewTimer(s scheduled, c TimerCallback) *Timer {
return &Timer{
Schedule: s,
callback: c,
refreshTimer: make(chan bool, 1),
skipWait: make(chan bool, 1),
quit: make(chan bool, 1),
isRunning: false,
err: nil,
}
}
func (t *Timer) IsRunning() bool {
t.rwLock.RLock()
defer t.rwLock.RUnlock()
return t.isRunning
}
func (t *Timer) Run() (*Timer, error) {
if t.err != nil {
return nil, t.err
}
durationToWait, err := t.Schedule.nextRun()
if err != nil {
return nil, err
}
if durationToWait < 0 {
return nil, ErrNoNextRun
}
wrapgo.GoWithDefaultPanicHandler(func() {
for shouldContinue := true; shouldContinue; {
if durationToWait < 0 {
return
}
shouldContinue = func () bool {
timer := time.NewTimer(durationToWait)
defer timer.Stop()
select {
case <- t.refreshTimer:
; // No-op. Just start next cycle with new interval
case <- t.skipWait:
wrapgo.GoWithDefaultPanicHandler(func () {
runTimer(t)
})
case <- t.quit:
return false
case <- timer.C:
wrapgo.GoWithDefaultPanicHandler(func () {
runTimer(t)
})
}
return true
}()
durationToWait, _ = t.Schedule.nextRun()
}
})
return t, nil
}
func (t *Timer) RefreshTimer() {
t.refreshTimer <- true
}
func (t *Timer) SkipWaiting() {
t.skipWait <- true
}
func (t *Timer) Stop() {
t.quit <- true
}
func (t *Timer) setRunning(state bool) {
t.rwLock.Lock()
defer t.rwLock.Unlock()
t.isRunning = state
}
func runTimer(t *Timer) {
if t.IsRunning() {
return
}
t.setRunning(true)
t.callback()
t.setRunning(false)
}