1
// Copyright 2015 Canonical Ltd.
2
// Licensed under the AGPLv3, see LICENCE file for details.
12
// Clock implements state/lease.Clock for testing purposes.
19
// NewClock returns a new clock set to the supplied time.
20
func NewClock(now time.Time) *Clock {
21
return &Clock{now: now}
24
// Now is part of the lease.Clock interface.
25
func (clock *Clock) Now() time.Time {
27
defer clock.mu.Unlock()
31
// Alarm is part of the lease.Clock interface.
32
func (clock *Clock) Alarm(t time.Time) <-chan time.Time {
34
defer clock.mu.Unlock()
35
notify := make(chan time.Time, 1)
36
if !clock.now.Before(t) {
39
clock.alarms = append(clock.alarms, alarm{t, notify})
40
sort.Sort(byTime(clock.alarms))
45
// Advance advances the result of Now by the supplied duration, and sends
46
// the "current" time on all alarms which are no longer "in the future".
47
func (clock *Clock) Advance(d time.Duration) {
49
defer clock.mu.Unlock()
50
clock.now = clock.now.Add(d)
52
for _, alarm := range clock.alarms {
53
if clock.now.Before(alarm.time) {
56
alarm.notify <- clock.now
59
clock.alarms = clock.alarms[rung:]
62
// alarm records the time at which we're expected to send on notify.
68
// byTime is used to sort alarms by time.
71
func (a byTime) Len() int { return len(a) }
72
func (a byTime) Less(i, j int) bool { return a[i].time.Before(a[j].time) }
73
func (a byTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }