golang-lib/worker/main.go

49 lines
826 B
Go
Raw Normal View History

2017-05-17 14:56:19 +02:00
// Package with a lib for cronjobs to run in background
package worker
2017-10-25 18:42:44 +02:00
import (
"sync"
"time"
)
2017-05-17 14:56:19 +02:00
// Struct which handles the job
type Worker struct {
every time.Duration
run func()
quit chan struct{}
2017-10-25 18:42:44 +02:00
wg sync.WaitGroup
2017-05-17 14:56:19 +02:00
}
// Function to create a new Worker with a timestamp, run, every and it's function
func NewWorker(every time.Duration, f func()) (w *Worker) {
w = &Worker{
every: every,
run: f,
quit: make(chan struct{}),
}
return
}
// Function to start the Worker
// (please us it as a go routine with go w.Start())
func (w *Worker) Start() {
2017-10-25 18:42:44 +02:00
w.wg.Add(1)
2017-05-17 14:56:19 +02:00
ticker := time.NewTicker(w.every)
for {
select {
case <-ticker.C:
w.run()
case <-w.quit:
ticker.Stop()
2017-10-25 18:42:44 +02:00
w.wg.Done()
2017-05-17 14:56:19 +02:00
return
}
}
}
// Function to stop the Worker
func (w *Worker) Close() {
close(w.quit)
2017-10-25 18:42:44 +02:00
w.wg.Wait()
2017-05-17 14:56:19 +02:00
}