github.com/MeteorsLiu/simpleMQ@v1.0.3/worker/worker_test.go (about) 1 package worker 2 3 import ( 4 "errors" 5 "fmt" 6 "sync" 7 "sync/atomic" 8 "testing" 9 "time" 10 11 "github.com/MeteorsLiu/simpleMQ/queue" 12 ) 13 14 func TestWorker(t *testing.T) { 15 q := queue.NewSimpleQueue() 16 w := NewWorker(5, 5, q) 17 var cnt atomic.Int64 18 var wg sync.WaitGroup 19 wg.Add(1) 20 w.Publish(queue.NewTask(func() error { 21 defer wg.Done() 22 c := cnt.Add(1) - 1 23 if c != 5 { 24 return fmt.Errorf("%d", c) 25 } 26 t.Log("success") 27 return nil 28 }, queue.WithNoRetryFunc())) 29 wg.Wait() 30 t.Log("start to execute the retry task") 31 cnt.Store(0) 32 var wg1 sync.WaitGroup 33 t1 := time.Now() 34 wg1.Add(6) 35 w.Publish(queue.NewTask(func() error { 36 defer wg1.Done() 37 c := cnt.Add(1) - 1 38 if c != 5 { 39 t.Log("retry fail", time.Since(t1)) 40 return fmt.Errorf("%d", c) 41 } 42 // 1+2+4+8+16 = 31s 43 t.Log("retry success", time.Since(t1)) 44 return nil 45 }, queue.WithRetryLimit(3))) 46 wg1.Wait() 47 t1 = time.Now() 48 task := queue.NewTask(func() error { 49 c := cnt.Add(1) - 1 50 if c != 5 { 51 return fmt.Errorf("%d", c) 52 } 53 // 1+2+4+8+16 = 31s 54 t.Log("retry success", time.Since(t1)) 55 return nil 56 }) 57 go func() { 58 time.AfterFunc(5*time.Second, func() { 59 task.Stop() 60 }) 61 }() 62 w.Publish(task) 63 time.Sleep(10 * time.Second) 64 } 65 66 func TestUnlimited(t *testing.T) { 67 w := NewWorker(0, 0, nil, true) 68 t.Log(w.unlimited) 69 var cnt atomic.Int64 70 t1 := time.Now() 71 task := queue.NewTask(func() error { 72 c := cnt.Add(1) - 1 73 if c != 5 { 74 return fmt.Errorf("%d", c) 75 } 76 return nil 77 }) 78 w.Publish(task, func(ok bool, task queue.Task) { 79 if ok { 80 // 1+2+4+8+16 = 31s 81 t.Log("retry success", time.Since(t1)) 82 } else { 83 // 1+2+4+8+16 = 31s 84 t.Log("retry fail", time.Since(t1)) 85 } 86 87 }) 88 w.Wait() 89 t1 = time.Now() 90 for i := 0; i < 2000; i++ { 91 w.Publish(queue.NewTask(func() error { 92 time.Sleep(10 * time.Second) 93 return nil 94 }), func(ok bool, task queue.Task) { 95 if ok { 96 // 1+2+4+8+16 = 31s 97 t.Log("retry success", time.Since(t1)) 98 } else { 99 // 1+2+4+8+16 = 31s 100 t.Log("retry fail", time.Since(t1)) 101 } 102 103 }) 104 } 105 w.Wait(5 * time.Second) 106 } 107 108 func TestWorkerOnce(t *testing.T) { 109 w := NewWorker(0, 0, nil) 110 neverStop := queue.NewTask(func() error { 111 t.Log("run once") 112 return errors.New("nerver stop") 113 }, queue.WithNoRetryFunc()) 114 115 w.Publish(neverStop) 116 117 neverStop.Wait() 118 } 119 120 func TestWorkerSync(t *testing.T) { 121 w := NewWorker(0, 0, nil) 122 task := queue.NewTask(func() error { 123 t.Log("run once") 124 return nil 125 }) 126 127 w.PublishSync(task) 128 129 t.Log(task.IsDone()) 130 } 131 132 func TestWorkerSyncOnce(t *testing.T) { 133 w := NewWorker(0, 0, nil) 134 neverStop := queue.NewTask(func() error { 135 t.Log("run once") 136 return errors.New("nerver stop") 137 }, queue.WithNoRetryFunc()) 138 139 w.PublishSync(neverStop) 140 }