-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
52 lines (48 loc) · 994 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
47
48
49
50
51
52
package task_runner
import "log"
/*
* Worker type.
* The task queue is the incoming tasks channel.
* The worker queue is the queue of workers it will add itself to.
* Stop channel to stop the worker.
*/
type Worker struct {
ID int
TaskQueue chan Task
WorkerQueue chan chan Task
StopSignal chan bool
log *log.Logger
}
func NewWorker(id int, workerQueue chan chan Task, logr *log.Logger) Worker {
worker := Worker{
ID: id,
TaskQueue: make(chan Task),
WorkerQueue: workerQueue,
StopSignal: make(chan bool),
log: logr,
}
return worker
}
func (w *Worker) Start () {
go func() {
w.log.Println("Worker starting")
for {
w.log.Println("Looking for work")
w.WorkerQueue <- w.TaskQueue
select {
case task := <- w.TaskQueue:
w.log.Println("Got work")
task.Execute()
case <- w.StopSignal:
w.log.Println("Stopping")
return
}
}
} ()
}
func (w * Worker) Stop() {
w.log.Println("Got stop signal")
go func() {
w.StopSignal <- true
} ()
}