-
Notifications
You must be signed in to change notification settings - Fork 739
/
ticker_task.go
53 lines (44 loc) · 960 Bytes
/
ticker_task.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
package task
import (
"time"
)
type Runner interface {
Run() error
}
type TickerTask struct {
interval time.Duration
runner Runner
done chan struct{}
}
func NewTickerTask(interval time.Duration, runner Runner) *TickerTask {
return &TickerTask{
interval: interval,
runner: runner,
done: make(chan struct{}),
}
}
// Start runs the task immediately and then schedules the task to run periodically
// if a positive fetching interval has been specified.
func (t *TickerTask) Start() {
t.runner.Run()
if t.interval > 0 {
go t.runRecurring()
}
}
// Stop stops the periodic task but the task runner maintains state
func (t *TickerTask) Stop() {
close(t.done)
}
// run creates a ticker that ticks at the specified interval. On each tick,
// the task is executed
func (t *TickerTask) runRecurring() {
ticker := time.NewTicker(t.interval)
for {
select {
case <-ticker.C:
t.runner.Run()
case <-t.done:
return
}
}
}