-
-
Notifications
You must be signed in to change notification settings - Fork 653
/
timer.go
67 lines (52 loc) · 1.13 KB
/
timer.go
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
package core
import (
"sync"
"time"
"github.com/benbjohnson/clock"
)
const wakeupTimeout = 30 * time.Second
const wakeupAttempts = 6 // wakeupAttempts is the count of wakeup attempts
// Timer measures active time between start and stop events
type Timer struct {
sync.Mutex
clck clock.Clock
started time.Time
wakeupAttemptsLeft int
}
// NewTimer creates timer that can expire
func NewTimer() *Timer {
return &Timer{
clck: clock.New(),
}
}
// Start starts the timer if not started already
func (m *Timer) Start() {
m.Lock()
defer m.Unlock()
m.wakeupAttemptsLeft = wakeupAttempts
if !m.started.IsZero() {
return
}
m.started = m.clck.Now()
}
// Reset resets the timer
func (m *Timer) Stop() {
m.Lock()
defer m.Unlock()
m.started = time.Time{}
}
// Expired checks if the timer has elapsed and if resets its status
func (m *Timer) Expired() bool {
m.Lock()
defer m.Unlock()
res := !m.started.IsZero() && (m.clck.Since(m.started) >= wakeupTimeout)
if res {
m.wakeupAttemptsLeft--
if m.wakeupAttemptsLeft == 0 {
m.started = time.Time{}
} else {
m.started = m.clck.Now()
}
}
return res
}