-
Notifications
You must be signed in to change notification settings - Fork 8
/
worker.go
61 lines (47 loc) · 876 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
53
54
55
56
57
58
59
60
61
package gottp
import (
"log"
"sync"
"time"
)
var worker func(chan bool)
var errChan = make(chan bool)
var exitChan = make(chan bool, 1)
var wg = new(sync.WaitGroup)
func spawner() {
go workerWrapper()
_, ok := <-errChan
if !ok {
log.Println("Timing out in 10 seconds")
time.Sleep(10 * time.Second)
wg.Done()
return
}
go spawner()
}
func workerWrapper() {
wg.Add(1)
defer wg.Done()
// Trusing the fact that Tracer will always execute callback.
defer Tracer.Notify(func(reason string) string {
errChan <- true
return "Exception in worker: " + reason
})
worker(exitChan)
}
func RunWorker(wk func(chan bool)) {
if worker != nil {
panic("Worker already running.")
}
worker = wk
go spawner()
}
func shutdownWorker() {
if worker == nil {
return
}
log.Println("Preparing for shutdown")
exitChan <- true
close(errChan)
wg.Wait()
}