forked from signalfx/golib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timekeeper.go
62 lines (49 loc) · 1.35 KB
/
timekeeper.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
package timekeeper
import "time"
// TimeKeeper is how we stub the progress of time in applications
type TimeKeeper interface {
Now() time.Time
Sleep(dur time.Duration)
After(d time.Duration) <-chan time.Time
NewTimer(d time.Duration) Timer
}
// Timer is an object that returns periodic timing events. We use the builtin time.NewTimer()
// generally but can also stub this out in constructors
type Timer interface {
Chan() <-chan time.Time
Stop() bool
}
// builtinTimer is a real-time timer
type builtinTimer struct {
timer *time.Timer
}
// Stop the internal timer
func (b *builtinTimer) Stop() bool {
return b.timer.Stop()
}
// Chan returns the single event channel for this timer
func (b *builtinTimer) Chan() <-chan time.Time {
return b.timer.C
}
var _ Timer = &builtinTimer{}
// RealTime calls bulit in time package functions that follow the real flow of time
type RealTime struct{}
var _ TimeKeeper = RealTime{}
// Now calls time.Now()
func (RealTime) Now() time.Time {
return time.Now()
}
// Sleep calls time.Sleep
func (RealTime) Sleep(dur time.Duration) {
time.Sleep(dur)
}
// After calls time.After
func (RealTime) After(d time.Duration) <-chan time.Time {
return time.After(d)
}
// NewTimer calls time.NewTimer and gives it a stubable interface
func (RealTime) NewTimer(d time.Duration) Timer {
return &builtinTimer{
timer: time.NewTimer(d),
}
}