github.com/wangyougui/gf/v2@v2.6.5/os/gtimer/gtimer_z_unit_internal_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 package gtimer 8 9 import ( 10 "context" 11 "testing" 12 "time" 13 14 "github.com/wangyougui/gf/v2/container/garray" 15 "github.com/wangyougui/gf/v2/test/gtest" 16 ) 17 18 func TestTimer_Proceed(t *testing.T) { 19 gtest.C(t, func(t *gtest.T) { 20 array := garray.New(true) 21 timer := New(TimerOptions{ 22 Interval: time.Hour, 23 }) 24 timer.Add(ctx, 10000*time.Hour, func(ctx context.Context) { 25 array.Append(1) 26 }) 27 timer.proceed(10001) 28 time.Sleep(10 * time.Millisecond) 29 t.Assert(array.Len(), 1) 30 timer.proceed(20001) 31 time.Sleep(10 * time.Millisecond) 32 t.Assert(array.Len(), 2) 33 }) 34 gtest.C(t, func(t *gtest.T) { 35 array := garray.New(true) 36 timer := New(TimerOptions{ 37 Interval: time.Millisecond * 100, 38 }) 39 timer.Add(ctx, 10000*time.Hour, func(ctx context.Context) { 40 array.Append(1) 41 }) 42 ticks := int64((10000 * time.Hour) / (time.Millisecond * 100)) 43 timer.proceed(ticks + 1) 44 time.Sleep(10 * time.Millisecond) 45 t.Assert(array.Len(), 1) 46 timer.proceed(2*ticks + 1) 47 time.Sleep(10 * time.Millisecond) 48 t.Assert(array.Len(), 2) 49 }) 50 } 51 52 func TestTimer_PriorityQueue(t *testing.T) { 53 gtest.C(t, func(t *gtest.T) { 54 queue := newPriorityQueue() 55 queue.Push(1, 1) 56 queue.Push(4, 4) 57 queue.Push(5, 5) 58 queue.Push(2, 2) 59 queue.Push(3, 3) 60 t.Assert(queue.Pop(), 1) 61 t.Assert(queue.Pop(), 2) 62 t.Assert(queue.Pop(), 3) 63 t.Assert(queue.Pop(), 4) 64 t.Assert(queue.Pop(), 5) 65 }) 66 } 67 68 func TestTimer_PriorityQueue_FirstOneInArrayIsTheLeast(t *testing.T) { 69 gtest.C(t, func(t *gtest.T) { 70 var ( 71 size = 1000000 72 array = garray.NewIntArrayRange(0, size, 1) 73 ) 74 array.Shuffle() 75 queue := newPriorityQueue() 76 array.Iterator(func(k int, v int) bool { 77 queue.Push(v, int64(v)) 78 return true 79 }) 80 for i := 0; i < size; i++ { 81 t.Assert(queue.Pop(), i) 82 t.Assert(queue.heap.array[0].priority, i+1) 83 } 84 }) 85 }