File: fake_timer.go

package info (click to toggle)
golang-github-pivotal-golang-clock 0.0~git20151018.0.3fd3c19-2.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 104 kB
  • sloc: makefile: 2
file content (79 lines) | stat: -rw-r--r-- 1,375 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package fakeclock

import (
	"sync"
	"time"
)

type fakeTimer struct {
	clock *FakeClock

	mutex          sync.Mutex
	completionTime time.Time
	channel        chan time.Time
	duration       time.Duration
	repeat         bool
}

func newFakeTimer(clock *FakeClock, d time.Duration, repeat bool) *fakeTimer {
	return &fakeTimer{
		clock:          clock,
		completionTime: clock.Now().Add(d),
		channel:        make(chan time.Time, 1),
		duration:       d,
		repeat:         repeat,
	}
}

func (ft *fakeTimer) C() <-chan time.Time {
	ft.mutex.Lock()
	defer ft.mutex.Unlock()
	return ft.channel
}

func (ft *fakeTimer) Reset(d time.Duration) bool {
	currentTime := ft.clock.Now()

	ft.mutex.Lock()
	active := !ft.completionTime.IsZero()
	ft.completionTime = currentTime.Add(d)
	ft.mutex.Unlock()

	ft.clock.addTimeWatcher(ft)

	return active
}

func (ft *fakeTimer) Stop() bool {
	ft.mutex.Lock()
	active := !ft.completionTime.IsZero()
	ft.completionTime = time.Time{}
	ft.mutex.Unlock()

	ft.clock.removeTimeWatcher(ft)

	return active
}

func (ft *fakeTimer) timeUpdated(now time.Time) {
	var fire bool

	ft.mutex.Lock()
	if !ft.completionTime.IsZero() {
		fire = now.After(ft.completionTime) || now.Equal(ft.completionTime)
	}
	ft.mutex.Unlock()

	if fire {
		select {
		case ft.channel <- now:
			ft.Stop()

		default:
		}

		if ft.repeat {
			ft.Reset(ft.duration)
		}
	}
}