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// PassiveClock allows for injecting fake or real clocks into code 22// that needs to read the current time but does not support scheduling 23// activity in the future. 24type PassiveClock interface { 25 Now() time.Time 26 Since(time.Time) time.Duration 27} 28 29// Clock allows for injecting fake or real clocks into code that 30// needs to do arbitrary things based on time. 31type Clock interface { 32 PassiveClock 33 After(d time.Duration) <-chan time.Time 34 NewTimer(d time.Duration) Timer 35 Sleep(d time.Duration) 36 Tick(d time.Duration) <-chan time.Time 37} 38 39var _ = Clock(RealClock{}) 40 41// RealClock really calls time.Now() 42type RealClock struct{} 43 44// Now returns the current time. 45func (RealClock) Now() time.Time { 46 return time.Now() 47} 48 49// Since returns time since the specified timestamp. 50func (RealClock) Since(ts time.Time) time.Duration { 51 return time.Since(ts) 52} 53 54// After is the same as time.After(d). 55func (RealClock) After(d time.Duration) <-chan time.Time { 56 return time.After(d) 57} 58 59// NewTimer is the same as time.NewTimer(d) 60func (RealClock) NewTimer(d time.Duration) Timer { 61 return &realTimer{ 62 timer: time.NewTimer(d), 63 } 64} 65 66// Tick is the same as time.Tick(d) 67func (RealClock) Tick(d time.Duration) <-chan time.Time { 68 return time.Tick(d) 69} 70 71// Sleep is the same as time.Sleep(d) 72func (RealClock) Sleep(d time.Duration) { 73 time.Sleep(d) 74} 75 76// Timer allows for injecting fake or real timers into code that 77// needs to do arbitrary things based on time. 78type Timer interface { 79 C() <-chan time.Time 80 Stop() bool 81 Reset(d time.Duration) bool 82} 83 84var _ = Timer(&realTimer{}) 85 86// realTimer is backed by an actual time.Timer. 87type realTimer struct { 88 timer *time.Timer 89} 90 91// C returns the underlying timer's channel. 92func (r *realTimer) C() <-chan time.Time { 93 return r.timer.C 94} 95 96// Stop calls Stop() on the underlying timer. 97func (r *realTimer) Stop() bool { 98 return r.timer.Stop() 99} 100 101// Reset calls Reset() on the underlying timer. 102func (r *realTimer) Reset(d time.Duration) bool { 103 return r.timer.Reset(d) 104} 105