forked from digitalocean/go-workers2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtask_runner.go
76 lines (63 loc) · 1.24 KB
/
task_runner.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
package workers
import (
"fmt"
"log"
"sync"
"time"
)
type taskRunner struct {
stop chan bool
handler JobFunc
currentMsg *Msg
lock sync.RWMutex
logger *log.Logger
}
func (w *taskRunner) quit() {
close(w.stop)
}
func (w *taskRunner) work(messages <-chan *Msg, done chan<- *Msg, ready chan<- bool) {
for {
select {
case msg := <-messages:
msg.startedAt = time.Now().UTC().Unix()
w.lock.Lock()
w.currentMsg = msg
w.lock.Unlock()
if err := w.process(msg); err != nil {
w.logger.Println("ERR:", err)
}
w.lock.Lock()
w.currentMsg = nil
w.lock.Unlock()
done <- msg
case ready <- true:
// Signaled to fetcher that we're
// ready to accept a message
case <-w.stop:
return
}
}
}
func (w *taskRunner) process(message *Msg) (err error) {
defer func() {
if e := recover(); e != nil {
var ok bool
if err, ok = e.(error); !ok {
err = fmt.Errorf("%v", e)
}
}
}()
return w.handler(message)
}
func (w *taskRunner) inProgressMessage() *Msg {
w.lock.RLock()
defer w.lock.RUnlock()
return w.currentMsg
}
func newTaskRunner(logger *log.Logger, handler JobFunc) *taskRunner {
return &taskRunner{
handler: handler,
stop: make(chan bool),
logger: logger,
}
}