2017-06-21 15:25:18 +02:00
|
|
|
// Package with a lib for cronjobs to run in the background
|
2017-04-05 20:23:29 +02:00
|
|
|
package worker
|
2017-04-05 19:03:44 +02:00
|
|
|
|
|
|
|
import "time"
|
|
|
|
|
2017-05-03 07:16:45 +02:00
|
|
|
// Struct which handles the job
|
2017-04-05 19:03:44 +02:00
|
|
|
type Worker struct {
|
|
|
|
every time.Duration
|
|
|
|
run func()
|
|
|
|
quit chan struct{}
|
|
|
|
}
|
|
|
|
|
2017-05-15 10:22:24 +02:00
|
|
|
// Function to create a new Worker with a timestamp, run, every and it's function
|
2017-04-05 19:03:44 +02:00
|
|
|
func NewWorker(every time.Duration, f func()) (w *Worker) {
|
|
|
|
w = &Worker{
|
|
|
|
every: every,
|
|
|
|
run: f,
|
|
|
|
quit: make(chan struct{}),
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-05-03 07:16:45 +02:00
|
|
|
// Function to start the Worker
|
2017-05-15 10:22:24 +02:00
|
|
|
// (please us it as a go routine with go w.Start())
|
2017-04-05 19:03:44 +02:00
|
|
|
func (w *Worker) Start() {
|
|
|
|
ticker := time.NewTicker(w.every)
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
|
|
|
w.run()
|
|
|
|
case <-w.quit:
|
|
|
|
ticker.Stop()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-04-28 10:27:36 +02:00
|
|
|
|
2017-05-03 07:16:45 +02:00
|
|
|
// Function to stop the Worker
|
2017-04-05 19:03:44 +02:00
|
|
|
func (w *Worker) Close() {
|
|
|
|
close(w.quit)
|
|
|
|
}
|