-
Notifications
You must be signed in to change notification settings - Fork 165
/
Copy pathworkers.go
129 lines (100 loc) · 1.96 KB
/
workers.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package workers
import (
"errors"
"fmt"
"log"
"net/http"
"os"
"sync"
)
const (
RETRY_KEY = "goretry"
SCHEDULED_JOBS_KEY = "schedule"
)
var Logger WorkersLogger = log.New(os.Stdout, "workers: ", log.Ldate|log.Lmicroseconds)
var managers = make(map[string]*manager)
var schedule *scheduled
var control = make(map[string]chan string)
var access sync.Mutex
var started bool
var Middleware = NewMiddleware(
&MiddlewareLogging{},
&MiddlewareRetry{},
&MiddlewareStats{},
)
func Process(queue string, job jobFunc, concurrency int, mids ...Action) {
access.Lock()
defer access.Unlock()
managers[queue] = newManager(queue, job, concurrency, mids...)
}
func Run() {
Start()
go handleSignals()
waitForExit()
}
func ResetManagers() error {
access.Lock()
defer access.Unlock()
if started {
return errors.New("Cannot reset worker managers while workers are running")
}
managers = make(map[string]*manager)
return nil
}
func Start() {
access.Lock()
defer access.Unlock()
if started {
return
}
runHooks(beforeStart)
startSchedule()
startManagers()
started = true
}
func Quit() {
access.Lock()
defer access.Unlock()
if !started {
return
}
quitManagers()
quitSchedule()
runHooks(duringDrain)
waitForExit()
started = false
}
func StatsServer(port int) {
http.HandleFunc("/stats", Stats)
Logger.Println("Stats are available at", fmt.Sprint("http://localhost:", port, "/stats"))
if err := http.ListenAndServe(fmt.Sprint(":", port), nil); err != nil {
Logger.Println(err)
}
}
func startSchedule() {
if schedule == nil {
schedule = newScheduled(RETRY_KEY, SCHEDULED_JOBS_KEY)
}
schedule.start()
}
func quitSchedule() {
if schedule != nil {
schedule.quit()
schedule = nil
}
}
func startManagers() {
for _, manager := range managers {
manager.start()
}
}
func quitManagers() {
for _, m := range managers {
go (func(m *manager) { m.quit() })(m)
}
}
func waitForExit() {
for _, manager := range managers {
manager.Wait()
}
}