-
Notifications
You must be signed in to change notification settings - Fork 1
/
timers.go
87 lines (71 loc) · 1.8 KB
/
timers.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 wbgong
import (
"time"
)
// Timer is fakeable timer interface
type Timer interface {
// GetChannel retrieves a channel that signals timer expiration
GetChannel() <-chan time.Time
// Stop stops the timer
Stop()
}
// RTimer is reusable Timer with Reset method
type RTimer interface {
// embed generic Timer here
Timer
// Reset changes the timer to expire after new duration d
Reset(d time.Duration)
}
// RealTicker incapsulates a real time.Ticker
type RealTicker struct {
innerTicker *time.Ticker
}
func NewRealTicker(d time.Duration) *RealTicker {
return &RealTicker{time.NewTicker(d)}
}
func (ticker *RealTicker) GetChannel() <-chan time.Time {
if ticker.innerTicker == nil {
panic("trying to get channel from a stopped ticker")
}
return ticker.innerTicker.C
}
func (ticker *RealTicker) Stop() {
if ticker.innerTicker != nil {
ticker.innerTicker.Stop()
ticker.innerTicker = nil
}
}
// RealTimer incapsulates a real time.Ticker
type RealTimer struct {
innerTimer *time.Timer
}
func NewRealTimer(d time.Duration) *RealTimer {
return &RealTimer{time.NewTimer(d)}
}
func (timer *RealTimer) GetChannel() <-chan time.Time {
if timer.innerTimer == nil {
panic("trying to get channel from a stopped timer")
}
return timer.innerTimer.C
}
func (timer *RealTimer) Stop() {
if timer.innerTimer != nil {
timer.innerTimer.Stop()
timer.innerTimer = nil
}
}
// RealRTimer incapsulates a real time.Timer with Reset() method
type RealRTimer struct {
RealTimer
}
// Reset resets an existing timer or creates a new one with given duration
func (timer *RealRTimer) Reset(d time.Duration) {
if timer.innerTimer == nil {
timer.innerTimer = time.NewTimer(d)
} else {
timer.innerTimer.Reset(d)
}
}
func NewRealRTimer(d time.Duration) *RealRTimer {
return &RealRTimer{RealTimer{time.NewTimer(d)}}
}