OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 package testclock |
| 6 |
| 7 import ( |
| 8 "time" |
| 9 |
| 10 "infra/libs/clock" |
| 11 ) |
| 12 |
| 13 // timer is an implementation of clock.TestTimer that uses a channel |
| 14 // to signal the timer to fire. |
| 15 // |
| 16 // The channel is buffered so it can be used without requiring a separate signal
ling |
| 17 // goroutine. |
| 18 type timer struct { |
| 19 clock *testClock // The underlying test clock instance. |
| 20 signalC chan time.Time // Underlying signal channel. |
| 21 |
| 22 // Cancels callback from clock.invokeAt. Being not nil implies that the
timer |
| 23 // is active. |
| 24 cancelFunc cancelFunc |
| 25 } |
| 26 |
| 27 var _ clock.Timer = (*timer)(nil) |
| 28 |
| 29 // NewTimer returns a new, instantiated timer. |
| 30 func newTimer(clock *testClock) clock.Timer { |
| 31 t := timer{ |
| 32 clock: clock, |
| 33 } |
| 34 return &t |
| 35 } |
| 36 |
| 37 func (t *timer) GetC() (c <-chan time.Time) { |
| 38 if t.cancelFunc != nil { |
| 39 c = t.signalC |
| 40 } |
| 41 return |
| 42 } |
| 43 |
| 44 func (t *timer) Reset(d time.Duration) (active bool) { |
| 45 now := t.clock.Now() |
| 46 triggerTime := now.Add(d) |
| 47 |
| 48 // Signal our timerSet callback. |
| 49 t.clock.signalTimerSet(t) |
| 50 |
| 51 // Stop our current polling goroutine, if it's running. |
| 52 active = t.Stop() |
| 53 |
| 54 // Set timer properties. |
| 55 t.signalC = make(chan time.Time, 1) |
| 56 t.cancelFunc = t.clock.invokeAt(triggerTime, t.signal) |
| 57 return |
| 58 } |
| 59 |
| 60 func (t *timer) Stop() bool { |
| 61 // If the timer is not running, we're done. |
| 62 if t.cancelFunc == nil { |
| 63 return false |
| 64 } |
| 65 |
| 66 // Clear our state. |
| 67 t.cancelFunc() |
| 68 t.cancelFunc = nil |
| 69 return true |
| 70 } |
| 71 |
| 72 // Sends a single signal, clearing the channel afterwards. |
| 73 func (t *timer) signal(now time.Time) { |
| 74 if t.signalC != nil { |
| 75 t.signalC <- now |
| 76 } |
| 77 } |
OLD | NEW |