[TASK] add worker
This commit is contained in:
parent
5240050a5a
commit
ea2b3e03f3
|
@ -0,0 +1,41 @@
|
||||||
|
// Package with a lib for cronjobs to run in background
|
||||||
|
package worker
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// Struct which handles the job
|
||||||
|
type Worker struct {
|
||||||
|
every time.Duration
|
||||||
|
run func()
|
||||||
|
quit chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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() {
|
||||||
|
ticker := time.NewTicker(w.every)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
w.run()
|
||||||
|
case <-w.quit:
|
||||||
|
ticker.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function to stop the Worker
|
||||||
|
func (w *Worker) Close() {
|
||||||
|
close(w.quit)
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
// Package with a lib for cronjobs to run in background
|
||||||
|
package worker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Function to test the Worker
|
||||||
|
func TestWorker(t *testing.T) {
|
||||||
|
assert := assert.New(t)
|
||||||
|
|
||||||
|
runtime := 0
|
||||||
|
|
||||||
|
w := NewWorker(time.Duration(5)*time.Millisecond, func() {
|
||||||
|
runtime = runtime + 1
|
||||||
|
})
|
||||||
|
go w.Start()
|
||||||
|
time.Sleep(time.Duration(18) * time.Millisecond)
|
||||||
|
w.Close()
|
||||||
|
|
||||||
|
assert.Equal(3, runtime)
|
||||||
|
time.Sleep(time.Duration(8) * time.Millisecond)
|
||||||
|
}
|
Loading…
Reference in New Issue