-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathworker.go
More file actions
113 lines (98 loc) · 2.11 KB
/
Copy pathworker.go
File metadata and controls
113 lines (98 loc) · 2.11 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package bgjob
import (
"context"
"sync"
"time"
)
type Handler interface {
Handle(ctx context.Context, job Job) Result
}
type HandlerFunc func(ctx context.Context, job Job) Result
func (h HandlerFunc) Handle(ctx context.Context, job Job) Result {
return h(ctx, job)
}
type Worker struct {
cli *Client
queue string
handler Handler
pollInterval time.Duration
concurrency int
wg *sync.WaitGroup
observer Observer
close chan struct{}
}
func NewWorker(cli *Client, queue string, handler Handler, opts ...WorkerOption) *Worker {
w := &Worker{
cli: cli,
queue: queue,
handler: handler,
pollInterval: 1 * time.Second,
concurrency: 1,
wg: &sync.WaitGroup{},
close: make(chan struct{}),
observer: NewNoopObserver(),
}
for _, opt := range opts {
opt(w)
}
return w
}
func (w *Worker) Run(ctx context.Context) {
for i := 0; i < w.concurrency; i++ {
w.wg.Add(1)
go w.run(ctx)
}
}
func (w *Worker) run(ctx context.Context) {
defer w.wg.Done()
for {
select {
case <-w.close:
return
default:
}
var lastResult Result
var lastJob Job
err := w.cli.Do(ctx, w.queue, func(ctx context.Context, job Job) Result {
w.observer.JobStarted(ctx, job)
result := w.handler.Handle(ctx, job)
lastResult = result
lastJob = job
return result
})
if err != nil {
if err == ErrEmptyQueue {
w.observer.QueueIsEmpty(ctx)
} else {
w.observer.WorkerError(ctx, err)
}
select {
case <-ctx.Done():
return
case <-w.close:
return
case <-time.After(w.pollInterval):
}
continue
}
if lastResult.overrideArg {
lastJob.Arg = lastResult.arg
}
if lastResult.complete {
w.observer.JobCompleted(ctx, lastJob)
}
if lastResult.retry {
w.observer.JobWillBeRetried(ctx, lastJob, lastResult.retryDelay, lastResult.err)
}
if lastResult.moveToDlq {
w.observer.JobMovedToDlq(ctx, lastJob, lastResult.err)
}
if lastResult.reschedule {
w.observer.JobRescheduled(ctx, lastJob, lastResult.rescheduleDelay)
}
}
}
func (w *Worker) Shutdown() {
close(w.close)
w.wg.Wait()
}