-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
82 lines (68 loc) · 1.39 KB
/
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
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
package sanji
import (
"sync/atomic"
"time"
"github.com/bitleak/lmstfy/client"
)
type iworker interface {
start()
quit()
work(jobs chan *client.Job)
process(job *client.Job) bool
processing() bool
}
type worker struct {
manager *manager
stop chan struct{}
exit chan struct{}
currentJob *client.Job
startedAt int64
}
func (w *worker) start() {
go w.work(w.manager.fetch.Messages())
}
func (w *worker) quit() {
w.stop <- struct{}{}
<-w.exit
}
func (w *worker) work(jobs chan *client.Job) {
for {
select {
case job := <-jobs:
atomic.StoreInt64(&w.startedAt, time.Now().UTC().Unix())
w.currentJob = job
if w.process(job) {
w.manager.confirm <- job
}
atomic.StoreInt64(&w.startedAt, time.Now().UTC().Unix())
w.currentJob = nil
select {
case w.manager.fetch.FinishedWork() <- struct{}{}:
default:
}
case w.manager.fetch.Ready() <- struct{}{}:
case <-w.stop:
w.exit <- struct{}{}
return
}
}
}
func (w *worker) process(job *client.Job) bool {
ctx := &Context{
Queue: w.manager.queue,
Job: job,
acknowledge: true,
handlers: w.manager.handlers,
}
defer func() {
recover()
}()
ctx.Next()
return ctx.acknowledge
}
func (w *worker) processing() bool {
return atomic.LoadInt64(&w.startedAt) > 0
}
func newWorker(m *manager) iworker {
return &worker{m, make(chan struct{}), make(chan struct{}), nil, 0}
}