99 "github.com/golang-queue/nsq"
1010 "github.com/golang-queue/queue"
1111 "github.com/golang-queue/queue/core"
12+
13+ "github.com/appleboy/graceful"
1214)
1315
1416type job struct {
@@ -27,36 +29,54 @@ func main() {
2729 taskN := 10000
2830 rets := make (chan string , taskN )
2931
32+ m := graceful .NewManager ()
33+
3034 // define the worker
3135 w := nsq .NewWorker (
3236 nsq .WithAddr ("127.0.0.1:4150" ),
3337 nsq .WithTopic ("example" ),
3438 nsq .WithChannel ("foobar" ),
35- // concurrent job number
36- nsq .WithMaxInFlight (10 ),
3739 nsq .WithRunFunc (func (ctx context.Context , m core.QueuedMessage ) error {
3840 var v * job
3941 if err := json .Unmarshal (m .Bytes (), & v ); err != nil {
4042 return err
4143 }
4244 rets <- v .Message
43- time .Sleep (6 * time .Second )
45+ fmt .Println ("got message:" , v .Message )
46+ fmt .Println ("wait 10 seconds" )
47+ time .Sleep (10 * time .Second )
4448 return nil
4549 }),
4650 )
4751
4852 // define the queue
4953 q := queue .NewPool (
50- 5 ,
54+ 1 ,
5155 queue .WithWorker (w ),
5256 )
5357
54- // wait until all tasks done
55- for i := 0 ; i < taskN ; i ++ {
56- fmt .Println ("message:" , <- rets )
57- time .Sleep (50 * time .Millisecond )
58- }
58+ m .AddRunningJob (func (ctx context.Context ) error {
59+ for {
60+ select {
61+ case <- ctx .Done ():
62+ select {
63+ case m := <- rets :
64+ fmt .Println ("message:" , m )
65+ default :
66+ }
67+ return nil
68+ case m := <- rets :
69+ fmt .Println ("message:" , m )
70+ time .Sleep (50 * time .Millisecond )
71+ }
72+ }
73+ })
74+
75+ m .AddShutdownJob (func () error {
76+ // shutdown the service and notify all the worker
77+ q .Release ()
78+ return nil
79+ })
5980
60- // shutdown the service and notify all the worker
61- q .Release ()
81+ <- m .Done ()
6282}
0 commit comments