-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.go
87 lines (69 loc) · 1.55 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
package timer
import (
"math/rand"
"time"
)
type Timer interface {
Reset(time.Duration) bool
Stop() bool
Wait()
Channel() <-chan time.Time
}
type Ticker time.Ticker
func (t *Ticker) Stop() bool {
(*time.Ticker)(t).Stop()
return true
}
func (t *Ticker) Reset(d time.Duration) bool {
(*time.Ticker)(t).Reset(d)
return true
}
func (t *Ticker) Wait() {
<-t.C
}
func (t *Ticker) Channel() <-chan time.Time {
return t.C
}
func NewTimer(interval time.Duration) Timer {
return (*Ticker)(time.NewTicker(interval))
}
var _ Timer = &RandTimer{}
type RandTimer struct {
timer *time.Timer
limitBase, limitRange time.Duration
}
func (t *RandTimer) Stop() bool {
return t.timer.Stop()
}
// 设置最小间隔
func (t *RandTimer) Reset(d time.Duration) bool {
t.limitBase = d
return t.reset()
}
func (t *RandTimer) reset() bool {
if t.limitRange == 0 {
return t.timer.Reset(t.limitBase)
}
return t.timer.Reset(t.limitBase + time.Duration(rand.Intn(int(t.limitRange))))
}
func (t *RandTimer) Wait() {
<-t.timer.C
t.reset()
}
func (t *RandTimer) Channel() <-chan time.Time {
return t.timer.C
}
// minInterval:最小等待时间
// maxInterval:最大等待时间
// maxInterval-minInterval: 等待范围
func NewRandTimer(minInterval, maxInterval time.Duration) Timer {
limitRange := maxInterval - minInterval
if limitRange == 0 {
return (*Ticker)(time.NewTicker(minInterval))
}
return &RandTimer{
timer: time.NewTimer(minInterval + time.Duration(rand.Intn(int(limitRange)))),
limitBase: minInterval,
limitRange: limitRange,
}
}