-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
46 lines (40 loc) · 971 Bytes
/
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
package minion
// Job describes a job to perform. The implementing struct can contain whatever additional fields
// it requires to perform its job when Perform() runs.
type Job interface {
// Perform runs the job.
Perform()
}
// Worker waits for incoming jobs on its channel and performs them.
type Worker struct {
workerPool chan chan Job
jobChannel chan Job
quit chan bool
}
// NewWorker creates a new worker connected to the provided worker pool.
func NewWorker(pool chan chan Job) Worker {
return Worker{
workerPool: pool,
jobChannel: make(chan Job),
quit: make(chan bool),
}
}
// Start starts the worker, waiting for incoming jobs on its job channel.
func (w Worker) Start() {
go func() {
for {
// Register worker in pool
w.workerPool <- w.jobChannel
select {
case job := <-w.jobChannel:
job.Perform()
case <-w.quit:
return
}
}
}()
}
// Stop stops the worker.
func (w Worker) Stop() {
w.quit <- true
}