-
Notifications
You must be signed in to change notification settings - Fork 0
/
jobQueue.go
66 lines (53 loc) · 1.05 KB
/
jobQueue.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
package goworker
import (
"fmt"
"runtime"
"time"
)
type jobQueue_ struct {
queue chan func()
workQueue chan int //当前工作者
}
//实例化一个jobQueue
func newJobQueue(maxQueue int, maxWorker int) *jobQueue_ {
jq := new(jobQueue_)
jq.queue = make(chan func(), maxQueue)
jq.workQueue = make(chan int, maxWorker)
go func() {
for {
select {
case jobInfo := <-jq.queue:
jq.workQueue <- 1
jq.DoJob(jobInfo)
}
}
}()
return jq
}
func (jq *jobQueue_) PushJob(job func()) {
jq.queue <- job
}
func (jq *jobQueue_) GetJob() <-chan func() {
return jq.queue
}
func (jq *jobQueue_) DoJob(job func()) {
go func() {
st := time.Now()
defer func() {
<-jq.workQueue
if onInfoLog != nil {
onInfoLog("任务执行时间:" + time.Now().Sub(st).String())
}
if r := recover(); r != nil {
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
if onErrorLog != nil {
onErrorLog(fmt.Sprintf("worker panic : %s\n%s", r, buf))
}
}
}()
//执行job
job()
}()
}