Jiri Simsa | 5293dcb | 2014-05-10 09:56:38 -0700 | [diff] [blame] | 1 | package timekeeper |
| 2 | |
| 3 | import "time" |
| 4 | |
| 5 | // TimeKeeper is meant as a drop-in replacement for using the time package |
| 6 | // directly, and allows testing code to substitute a suitable implementation. |
| 7 | // The meaning of duration and current time depends on the implementation (may |
| 8 | // be a simulated time). |
| 9 | type TimeKeeper interface { |
| 10 | // After waits for the duration to elapse and then sends the current |
| 11 | // time on the returned channel. |
| 12 | After(d time.Duration) <-chan time.Time |
| 13 | // Sleep pauses the current goroutine for at least the duration d. A |
| 14 | // negative or zero duration causes Sleep to return immediately. |
| 15 | Sleep(d time.Duration) |
| 16 | } |
| 17 | |
| 18 | // realTime is the default implementation of TimeKeeper, using the time package. |
| 19 | type realTime struct{} |
| 20 | |
| 21 | var rt realTime |
| 22 | |
| 23 | // After implements TimeKeeper.After. |
| 24 | func (t *realTime) After(d time.Duration) <-chan time.Time { |
| 25 | return time.After(d) |
| 26 | } |
| 27 | |
| 28 | // Sleep implements TimeKeeper.Sleep. |
| 29 | func (t *realTime) Sleep(d time.Duration) { |
| 30 | time.Sleep(d) |
| 31 | } |
| 32 | |
| 33 | // RealTime returns a default instance of TimeKeeper. |
| 34 | func RealTime() TimeKeeper { |
| 35 | return &rt |
| 36 | } |