-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathticker.go
57 lines (49 loc) · 1.11 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
package ticker
import (
"errors"
"time"
"github.com/tilinna/clock"
)
// Config defines the necessary information and dependencies to instantiate a Ticker
type Config struct {
Clock clock.Clock
Interval time.Duration
Callback func()
}
// Ticker represents a periodic timer that invokes a callback
type Ticker struct {
quitC chan struct{}
}
// ErrAlreadyStopped is returned if this service was already stopped and Stop() is called again
var ErrAlreadyStopped = errors.New("Already stopped")
// New builds a ticker that will call the given callback function periodically
func New(config *Config) *Ticker {
tk := &Ticker{
quitC: make(chan struct{}),
}
if config.Clock == nil {
config.Clock = clock.Realtime()
}
ticker := config.Clock.NewTicker(config.Interval)
go func() {
defer ticker.Stop()
for {
select {
case <-ticker.C:
config.Callback()
case <-tk.quitC:
return
}
}
}()
return tk
}
// Stop stops the timer and releases the goroutine running it.
func (tk *Ticker) Stop() error {
if tk.quitC == nil {
return ErrAlreadyStopped
}
close(tk.quitC)
tk.quitC = nil
return nil
}