File tree Expand file tree Collapse file tree 2 files changed +24
-15
lines changed Expand file tree Collapse file tree 2 files changed +24
-15
lines changed Original file line number Diff line number Diff line change 1
1
package queue
2
2
3
3
import (
4
+ "encoding/json"
4
5
"errors"
5
6
"runtime"
6
7
"sync"
@@ -37,6 +38,11 @@ func (j Job) Bytes() []byte {
37
38
return j .Body
38
39
}
39
40
41
+ func (j Job ) Encode () []byte {
42
+ b , _ := json .Marshal (j )
43
+ return b
44
+ }
45
+
40
46
// Option for queue system
41
47
type Option func (* Queue )
42
48
@@ -126,28 +132,29 @@ func (q *Queue) Wait() {
126
132
q .routineGroup .Wait ()
127
133
}
128
134
129
- // Queue to queue all job
130
- func (q * Queue ) Queue (job QueuedMessage ) error {
135
+ func (q * Queue ) handleQueue (timeout time.Duration , job QueuedMessage ) error {
131
136
if atomic .LoadInt32 (& q .stopFlag ) == 1 {
132
137
return ErrQueueShutdown
133
138
}
134
139
135
- return q . worker . Queue ( Job {
136
- Timeout : q . timeout ,
140
+ data := Job {
141
+ Timeout : timeout ,
137
142
Body : job .Bytes (),
143
+ }
144
+
145
+ return q .worker .Queue (Job {
146
+ Body : data .Encode (),
138
147
})
139
148
}
140
149
141
150
// Queue to queue all job
142
- func (q * Queue ) QueueWithTimeout (timeout time.Duration , job QueuedMessage ) error {
143
- if atomic .LoadInt32 (& q .stopFlag ) == 1 {
144
- return ErrQueueShutdown
145
- }
151
+ func (q * Queue ) Queue (job QueuedMessage ) error {
152
+ return q .handleQueue (q .timeout , job )
153
+ }
146
154
147
- return q .worker .Queue (Job {
148
- Timeout : timeout ,
149
- Body : job .Bytes (),
150
- })
155
+ // Queue to queue all job
156
+ func (q * Queue ) QueueWithTimeout (timeout time.Duration , job QueuedMessage ) error {
157
+ return q .handleQueue (q .timeout , job )
151
158
}
152
159
153
160
func (q * Queue ) work () {
Original file line number Diff line number Diff line change @@ -2,6 +2,7 @@ package simple
2
2
3
3
import (
4
4
"context"
5
+ "encoding/json"
5
6
"errors"
6
7
"sync"
7
8
"sync/atomic"
@@ -39,11 +40,10 @@ func (s *Worker) AfterRun() error {
39
40
return nil
40
41
}
41
42
42
- func (s * Worker ) handle (m interface {} ) error {
43
+ func (s * Worker ) handle (job queue. Job ) error {
43
44
// create channel with buffer size 1 to avoid goroutine leak
44
45
done := make (chan error , 1 )
45
46
panicChan := make (chan interface {}, 1 )
46
- job , _ := m .(queue.Job )
47
47
startTime := time .Now ()
48
48
ctx , cancel := context .WithTimeout (context .Background (), job .Timeout )
49
49
defer cancel ()
@@ -95,7 +95,9 @@ func (s *Worker) Run() error {
95
95
}
96
96
97
97
for task := range s .taskQueue {
98
- if err := s .handle (task ); err != nil {
98
+ var data queue.Job
99
+ _ = json .Unmarshal (task .Bytes (), & data )
100
+ if err := s .handle (data ); err != nil {
99
101
s .logger .Error (err .Error ())
100
102
}
101
103
}
You can’t perform that action at this time.
0 commit comments