Download this file
| 1 | package isolatedjob |
| 2 | |
| 3 | import "time" |
| 4 | |
| 5 | // Clock gives the controller two readings. Wall is the calendar time, which |
| 6 | // can jump when the host clock is set. Mono is time elapsed since some fixed |
| 7 | // start; it never decreases, so deadlines and timeouts use it. |
| 8 | type Clock interface { |
| 9 | Wall() time.Time |
| 10 | Mono() time.Duration |
| 11 | } |
| 12 | |
| 13 | // SystemClock returns a Clock on this host's clocks. Mono is measured with |
| 14 | // Go's monotonic reading from the moment SystemClock is called. |
| 15 | func SystemClock() Clock { |
| 16 | return newSystemClock(time.Now, time.Since) |
| 17 | } |
| 18 | |
| 19 | // newSystemClock is SystemClock with its two clock sources passed in, so a |
| 20 | // test can move the wall clock back while elapsed time moves forward. |
| 21 | func newSystemClock(now func() time.Time, since func(time.Time) time.Duration) systemClock { |
| 22 | return systemClock{start: now(), now: now, since: since} |
| 23 | } |
| 24 | |
| 25 | type systemClock struct { |
| 26 | start time.Time // keeps Go's monotonic reading |
| 27 | now func() time.Time // the wall clock |
| 28 | since func(time.Time) time.Duration // elapsed time by the monotonic reading |
| 29 | } |
| 30 | |
| 31 | // Wall strips the monotonic reading, so a Wall value never stands in for Mono. |
| 32 | func (c systemClock) Wall() time.Time { return c.now().Round(0) } |
| 33 | |
| 34 | // Mono never reads the wall clock. |
| 35 | func (c systemClock) Mono() time.Duration { return c.since(c.start) } |
| 36 | |