-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.go
128 lines (106 loc) · 2.45 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package timer
import (
"time"
)
// Timer represents a monitor/iterator that runs
// a function on a given interval.
type Timer struct {
interval time.Duration
maxIntervals int
iterations int
fn func(args ...interface{})
args []interface{}
ticker *time.Ticker
process chan struct{}
running bool
}
// Start the timer.
func (timer *Timer) Start() {
if timer.running {
return
}
if timer.process != nil {
close(timer.process)
}
timer.running = true
timer.process = make(chan struct{})
timer.ticker = time.NewTicker(timer.interval)
timer.iterations = 0
go func(timer *Timer) {
for {
if timer.running {
select {
case <-timer.ticker.C:
go func(timer *Timer) {
if !timer.running {
return
}
timer.iterations = timer.iterations + 1
if timer.maxIntervals > 0 && timer.iterations > timer.maxIntervals {
timer.Stop()
return
}
timer.fn(timer.args...)
if timer.maxIntervals == 0 {
timer.Stop()
return
}
}(timer)
case <-timer.process:
timer.Stop()
return
}
} else {
return
}
}
}(timer)
}
// Stop the timer.
func (timer *Timer) Stop() {
if timer.running {
close(timer.process)
timer.running = false
}
}
// Count represents the number of times the interval has been processed.
func (timer *Timer) Count() int {
return timer.iterations
}
// Reset the timer
func (timer *Timer) Reset() {
timer.Stop()
timer.Start()
}
// IsRunning returns a boolean flag indicating whether the timer is running or not.
func (timer *Timer) IsRunning() bool {
if timer == nil {
return false
}
return timer.running
}
// SetInterval runs the specified function every `X` milliseconds, where
// `X` is the specified interval duration.
func SetInterval(fn func(args ...interface{}), duration int, args ...interface{}) *Timer {
timer := &Timer{
running: false,
interval: time.Duration(duration) * time.Millisecond,
fn: fn,
args: args,
maxIntervals: -1,
}
timer.Start()
return timer
}
// SetTimeout runs the specified function after waiting the specified duration (defined in milliseconds)
func SetTimeout(fn func(args ...interface{}), duration int, args ...interface{}) *Timer {
timer := &Timer{
running: false,
interval: time.Duration(duration) * time.Millisecond,
fn: fn,
args: args,
maxIntervals: 0,
}
timer.Start()
return timer
}