-
Notifications
You must be signed in to change notification settings - Fork 5
/
worker.go
49 lines (41 loc) · 836 Bytes
/
worker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main
import (
"context"
"sync"
)
// Worker is a worker for asynchronous jobs
type Worker struct {
ctx context.Context
wg sync.WaitGroup
cancel context.CancelFunc
err error
}
// NewWorker creates a new Worker with the ctx
func NewWorker(ctx context.Context) *Worker {
return &Worker{
ctx: ctx,
}
}
// Start starts a background job presented by f
func (w *Worker) Start(f func(ctx context.Context) error) {
if w.cancel != nil {
panic("worker is already started")
}
ctx, cancel := context.WithCancel(w.ctx)
w.cancel = cancel
w.wg.Add(1)
go func() {
w.err = f(ctx)
w.wg.Done()
}()
}
// Stop stops current asynchronous jobs and returns last error occurs in the job
func (w *Worker) Stop() error {
if w.cancel == nil {
return nil
}
w.cancel()
w.cancel = nil
w.wg.Wait()
return w.err
}