-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathtask_runner.go
93 lines (77 loc) · 1.56 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package workers
import (
"fmt"
"log"
"math/rand"
"sync"
"time"
)
type taskRunner struct {
stop chan bool
handler JobFunc
currentMsg *Msg
lock sync.RWMutex
logger *log.Logger
tid string
}
func (w *taskRunner) quit() {
close(w.stop)
}
var alphaNumericRunes = []rune("abcdefghijklmnopqrstuvwxyz1234567890")
func init() {
rand.Seed(time.Now().UnixNano())
}
func randSeq(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = alphaNumericRunes[rand.Intn(len(alphaNumericRunes))]
}
return string(b)
}
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,
tid: randSeq(3),
}
}