1/* 2Copyright 2014 The Kubernetes Authors. 3 4Licensed under the Apache License, Version 2.0 (the "License"); 5you may not use this file except in compliance with the License. 6You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10Unless required by applicable law or agreed to in writing, software 11distributed under the License is distributed on an "AS IS" BASIS, 12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13See the License for the specific language governing permissions and 14limitations under the License. 15*/ 16 17package clock 18 19import "time" 20 21// Clock allows for injecting fake or real clocks into code that 22// needs to do arbitrary things based on time. 23type Clock interface { 24 Now() time.Time 25 Since(time.Time) time.Duration 26 After(d time.Duration) <-chan time.Time 27 NewTimer(d time.Duration) Timer 28 Sleep(d time.Duration) 29 Tick(d time.Duration) <-chan time.Time 30} 31 32var _ = Clock(RealClock{}) 33 34// RealClock really calls time.Now() 35type RealClock struct{} 36 37// Now returns the current time. 38func (RealClock) Now() time.Time { 39 return time.Now() 40} 41 42// Since returns time since the specified timestamp. 43func (RealClock) Since(ts time.Time) time.Duration { 44 return time.Since(ts) 45} 46 47// After is the same as time.After(d). 48func (RealClock) After(d time.Duration) <-chan time.Time { 49 return time.After(d) 50} 51 52// NewTimer is the same as time.NewTimer(d) 53func (RealClock) NewTimer(d time.Duration) Timer { 54 return &realTimer{ 55 timer: time.NewTimer(d), 56 } 57} 58 59// Tick is the same as time.Tick(d) 60func (RealClock) Tick(d time.Duration) <-chan time.Time { 61 return time.Tick(d) 62} 63 64// Sleep is the same as time.Sleep(d) 65func (RealClock) Sleep(d time.Duration) { 66 time.Sleep(d) 67} 68 69// Timer allows for injecting fake or real timers into code that 70// needs to do arbitrary things based on time. 71type Timer interface { 72 C() <-chan time.Time 73 Stop() bool 74 Reset(d time.Duration) bool 75} 76 77var _ = Timer(&realTimer{}) 78 79// realTimer is backed by an actual time.Timer. 80type realTimer struct { 81 timer *time.Timer 82} 83 84// C returns the underlying timer's channel. 85func (r *realTimer) C() <-chan time.Time { 86 return r.timer.C 87} 88 89// Stop calls Stop() on the underlying timer. 90func (r *realTimer) Stop() bool { 91 return r.timer.Stop() 92} 93 94// Reset calls Reset() on the underlying timer. 95func (r *realTimer) Reset(d time.Duration) bool { 96 return r.timer.Reset(d) 97} 98