github.com/gofunct/common@v0.0.0-20190131174352-fd058c7fbf22/pkg/clock/clock.go (about) 1 package clock 2 3 import "time" 4 5 // Clock allows for injecting fake or real clocks into code that 6 // needs to do arbitrary things based on time. 7 type Clock interface { 8 Now() time.Time 9 Since(time.Time) time.Duration 10 After(d time.Duration) <-chan time.Time 11 NewTimer(d time.Duration) Timer 12 Sleep(d time.Duration) 13 Tick(d time.Duration) <-chan time.Time 14 } 15 16 var _ = Clock(RealClock{}) 17 18 // RealClock really calls time.Now() 19 type RealClock struct{} 20 21 // Now returns the current time. 22 func (RealClock) Now() time.Time { 23 return time.Now() 24 } 25 26 // Since returns time since the specified timestamp. 27 func (RealClock) Since(ts time.Time) time.Duration { 28 return time.Since(ts) 29 } 30 31 // After is the same as time.After(d). 32 func (RealClock) After(d time.Duration) <-chan time.Time { 33 return time.After(d) 34 } 35 36 // NewTimer is the same as time.NewTimer(d) 37 func (RealClock) NewTimer(d time.Duration) Timer { 38 return &realTimer{ 39 timer: time.NewTimer(d), 40 } 41 } 42 43 // Tick is the same as time.Tick(d) 44 func (RealClock) Tick(d time.Duration) <-chan time.Time { 45 return time.Tick(d) 46 } 47 48 // Sleep is the same as time.Sleep(d) 49 func (RealClock) Sleep(d time.Duration) { 50 time.Sleep(d) 51 } 52 53 // Timer allows for injecting fake or real timers into code that 54 // needs to do arbitrary things based on time. 55 type Timer interface { 56 C() <-chan time.Time 57 Stop() bool 58 Reset(d time.Duration) bool 59 } 60 61 var _ = Timer(&realTimer{}) 62 63 // realTimer is backed by an actual time.Timer. 64 type realTimer struct { 65 timer *time.Timer 66 } 67 68 // C returns the underlying timer's channel. 69 func (r *realTimer) C() <-chan time.Time { 70 return r.timer.C 71 } 72 73 // Stop calls Stop() on the underlying timer. 74 func (r *realTimer) Stop() bool { 75 return r.timer.Stop() 76 } 77 78 // Reset calls Reset() on the underlying timer. 79 func (r *realTimer) Reset(d time.Duration) bool { 80 return r.timer.Reset(d) 81 }