-
Notifications
You must be signed in to change notification settings - Fork 0
/
ticker.go
68 lines (61 loc) · 1.23 KB
/
ticker.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
package gon
import (
"sync"
"time"
)
// Ticker runs one or more functions, repeating at an interval.
type Ticker struct {
sync.RWMutex
wg sync.WaitGroup
duration time.Duration
ticker *time.Ticker
funcs map[int64]EventFunc
quit chan bool
}
// NewTicker creates the Ticker structure and quit channel.
func NewTicker(d time.Duration) *Ticker {
t := &Ticker{
duration: d,
funcs: make(map[int64]EventFunc)}
t.quit = make(chan bool)
return t
}
// AddFunc adds another callback to the funcs map with a new ID.
func (t *Ticker) AddFunc(f EventFunc, id int64) {
t.Lock()
defer t.Unlock()
t.funcs[id] = f
}
// Start creates the time.Ticker and handles the calls at intervals.
func (t *Ticker) Start() {
t.ticker = time.NewTicker(t.duration)
for {
select {
case <-t.ticker.C:
t.Lock()
for k, f := range t.funcs {
t.wg.Add(1)
go func(id int64, tf EventFunc) {
tf(id)
t.wg.Done()
}(k, f)
}
t.Unlock()
case <-t.quit:
t.ticker.Stop()
for k := range t.funcs {
delete(t.funcs, k)
}
return
}
}
}
// Stop the ticker.
func (t *Ticker) Stop() {
t.quit <- true
t.Wait()
}
// Wait for the current scheduled task in the ticker to finish.
func (t *Ticker) Wait() {
t.wg.Wait()
}