-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.go
54 lines (43 loc) · 863 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
package hal
import (
"time"
"github.com/benbjohnson/clock"
)
// Timer wraps time.Timer to add functionality for checking if the timer is running.
type Timer struct {
clock clock.Clock
timer *clock.Timer
running bool
}
func NewTimer(clock clock.Clock) *Timer {
return &Timer{
clock: clock,
}
}
func (t *Timer) Cancel() {
if t.timer == nil {
return
}
t.timer.Stop()
}
// Start starts the timer or resets it to a new duration.
func (t *Timer) Start(fn func(), duration time.Duration) {
if t.clock == nil {
t.clock = clock.New()
}
if t.timer == nil {
t.timer = t.clock.AfterFunc(duration, func() {
t.running = false
if fn != nil {
fn()
}
})
} else {
t.timer.Reset(duration)
}
t.running = true
}
// IsRunning returns whether the timer is currently running.
func (t *Timer) IsRunning() bool {
return t.running
}