github.com/gogf/gf@v1.16.9/os/gtimer/gtimer_z_unit_timer_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/gogf/gf.
     6  
     7  package gtimer
     8  
     9  import (
    10  	"github.com/gogf/gf/container/garray"
    11  	"github.com/gogf/gf/test/gtest"
    12  	"testing"
    13  	"time"
    14  )
    15  
    16  func TestTimer_Proceed(t *testing.T) {
    17  	gtest.C(t, func(t *gtest.T) {
    18  		array := garray.New(true)
    19  		timer := New(TimerOptions{
    20  			Interval: time.Hour,
    21  		})
    22  		timer.Add(10000*time.Hour, func() {
    23  			array.Append(1)
    24  		})
    25  		timer.proceed(10001)
    26  		time.Sleep(10 * time.Millisecond)
    27  		t.Assert(array.Len(), 1)
    28  		timer.proceed(20001)
    29  		time.Sleep(10 * time.Millisecond)
    30  		t.Assert(array.Len(), 2)
    31  	})
    32  	gtest.C(t, func(t *gtest.T) {
    33  		array := garray.New(true)
    34  		timer := New(TimerOptions{
    35  			Interval: time.Millisecond * 100,
    36  		})
    37  		timer.Add(10000*time.Hour, func() {
    38  			array.Append(1)
    39  		})
    40  		ticks := int64((10000 * time.Hour) / (time.Millisecond * 100))
    41  		timer.proceed(ticks + 1)
    42  		time.Sleep(10 * time.Millisecond)
    43  		t.Assert(array.Len(), 1)
    44  		timer.proceed(2*ticks + 1)
    45  		time.Sleep(10 * time.Millisecond)
    46  		t.Assert(array.Len(), 2)
    47  	})
    48  }
    49  
    50  func TestTimer_PriorityQueue(t *testing.T) {
    51  	gtest.C(t, func(t *gtest.T) {
    52  		queue := newPriorityQueue()
    53  		queue.Push(1, 1)
    54  		queue.Push(4, 4)
    55  		queue.Push(5, 5)
    56  		queue.Push(2, 2)
    57  		queue.Push(3, 3)
    58  		t.Assert(queue.Pop(), 1)
    59  		t.Assert(queue.Pop(), 2)
    60  		t.Assert(queue.Pop(), 3)
    61  		t.Assert(queue.Pop(), 4)
    62  		t.Assert(queue.Pop(), 5)
    63  	})
    64  }
    65  
    66  func TestTimer_PriorityQueue_FirstOneInArrayIsTheLeast(t *testing.T) {
    67  	gtest.C(t, func(t *gtest.T) {
    68  		var (
    69  			size  = 1000000
    70  			array = garray.NewIntArrayRange(0, size, 1)
    71  		)
    72  		array.Shuffle()
    73  		queue := newPriorityQueue()
    74  		array.Iterator(func(k int, v int) bool {
    75  			queue.Push(v, int64(v))
    76  			return true
    77  		})
    78  		for i := 0; i < size; i++ {
    79  			t.Assert(queue.Pop(), i)
    80  			t.Assert(queue.heap.array[0].priority, i+1)
    81  		}
    82  	})
    83  }