-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
107 lines (93 loc) · 2.2 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
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
package ozero
import (
"fmt"
"time"
)
// WorkerFunc defines a function that receives a job and processes it.
type WorkerFunc func(interface{}) error
func (pool *Pool) worker() {
var job job
// Catch panics and notify of exit.
defer func() {
if r := recover(); nil != r {
err, ok := r.(error)
if !ok {
err = fmt.Errorf("pkg: %v", r)
}
pool.mutex.RLock()
defer pool.mutex.RUnlock()
if nil != pool.errorFunc {
pool.errorFunc(job.Data, err)
}
}
pool.workerExitedCh <- struct{}{}
}()
for job = range pool.jobsCh {
pool.mutex.RLock()
f := pool.workerFunc
tries := pool.totalTryCount
delay := pool.retryTimeout
shouldRetryFunc := pool.shouldRetryFunc
pool.mutex.RUnlock()
if nil != f {
var err error
var currentTry = 0
for {
err = pool.work(f, job.Data)
if nil == err { // Executed successfully
break
}
if 0 != tries { // Maximum try count not infinite.
currentTry++
if currentTry >= tries { // Maximum try count exceeded.
break
}
}
if nil != shouldRetryFunc {
if !shouldRetryFunc(job.Data, err, currentTry-1) {
break
}
}
time.Sleep(delay)
}
if nil != err {
panic(err)
}
}
}
}
func (pool *Pool) work(f WorkerFunc, data interface{}) (ret error) {
// Catch panics and notify of exit.
defer func() {
if r := recover(); nil != r {
err, ok := r.(error)
if !ok {
err = fmt.Errorf("pkg: %v", r)
}
ret = err
}
}()
return f(data)
}
// SetWorkerFunc sets the function to be processed when sending jobs to the worker.
func (pool *Pool) SetWorkerFunc(f WorkerFunc) *Pool {
pool.mutex.Lock()
defer pool.mutex.Unlock()
pool.workerFunc = f
return pool
}
// SetErrorFunc sets the function to be executed when a panic occurrs in a worker.
// If nil, nothing gets executed on panic.
func (pool *Pool) SetErrorFunc(f ErrorFunc) *Pool {
pool.mutex.Lock()
defer pool.mutex.Unlock()
pool.errorFunc = f
return pool
}
// SetShouldRetryFunc sets a function to be executed when a panic occurrs, to determine if the job should be retried.
func (pool *Pool) SetShouldRetryFunc(f ShouldRetryFunc) *Pool {
pool.mutex.Lock()
defer pool.mutex.Unlock()
pool.shouldRetryFunc = f
return pool
}