forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.go
57 lines (44 loc) · 898 Bytes
/
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
package core
import (
"sync"
"time"
"github.com/benbjohnson/clock"
)
const wakeupTimeout = 30 * time.Second
// Timer measures active time between start and stop events
type Timer struct {
sync.Mutex
clck clock.Clock
started time.Time
}
// 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()
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.started = time.Time{}
}
return res
}