This repository has been archived on 2020-09-27. You can view files and clone it, but cannot push or open issues or pull requests.
2017-04-05 20:23:29 +02:00
|
|
|
package worker
|
2017-04-05 19:03:44 +02:00
|
|
|
|
|
|
|
import "time"
|
|
|
|
|
|
|
|
type Worker struct {
|
|
|
|
every time.Duration
|
|
|
|
run func()
|
|
|
|
quit chan struct{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewWorker(every time.Duration, f func()) (w *Worker) {
|
|
|
|
w = &Worker{
|
|
|
|
every: every,
|
|
|
|
run: f,
|
|
|
|
quit: make(chan struct{}),
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *Worker) Start() {
|
|
|
|
ticker := time.NewTicker(w.every)
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
|
|
|
w.run()
|
|
|
|
case <-w.quit:
|
|
|
|
ticker.Stop()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
func (w *Worker) Close() {
|
|
|
|
close(w.quit)
|
|
|
|
}
|