golang-lib/worker/main.go

50 lines
799 B
Go
Raw Permalink Normal View History

// Package worker to run functions like a cronjob in background
2017-05-17 14:56:19 +02:00
package worker
2017-10-25 18:42:44 +02:00
import (
"sync"
"time"
)
2017-05-17 14:56:19 +02:00
2018-08-23 21:02:51 +02:00
// Worker Struct which handles the job
2017-05-17 14:56:19 +02:00
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
}
2018-08-23 21:02:51 +02:00
// NewWorker create a Worker with a timestamp, run, every and it's function
2017-05-17 14:56:19 +02:00
func NewWorker(every time.Duration, f func()) (w *Worker) {
w = &Worker{
every: every,
run: f,
quit: make(chan struct{}),
}
return
}
2018-08-23 21:02:51 +02:00
// Start the Worker
2017-05-17 14:56:19 +02:00
func (w *Worker) Start() {
2017-10-25 18:42:44 +02:00
w.wg.Add(1)
2018-03-22 22:10:05 +01:00
go func() {
defer w.wg.Done()
ticker := time.NewTicker(w.every)
for {
select {
case <-ticker.C:
w.run()
case <-w.quit:
ticker.Stop()
return
}
2017-05-17 14:56:19 +02:00
}
2018-03-22 22:10:05 +01:00
}()
2017-05-17 14:56:19 +02:00
}
2018-08-23 21:02:51 +02:00
// Close stops the Worker
2017-05-17 14:56:19 +02:00
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
}