github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/time/test/timer_test.go (about)

     1  package test
     2  
     3  import (
     4  	"testing"
     5  
     6  	t0 "time"
     7  
     8  	"github.com/isyscore/isc-gobase/time"
     9  )
    10  
    11  func TestTimer(t *testing.T) {
    12  
    13  	globalCount := 0
    14  	timer := time.NewTimerWithFire(1.5, func(tm *time.Timer) {
    15  		// 这里是运行在协程内的
    16  		globalCount++
    17  		t.Logf("globalCount: %d", globalCount)
    18  	})
    19  	timer.Start()
    20  	t.Logf("timer.stopped = %v\n", timer.IsStopped)
    21  
    22  	// 等待timer执行5次
    23  	for globalCount != 5 {
    24  		t0.Sleep(t0.Second)
    25  	}
    26  
    27  	timer.Stop()
    28  	t.Logf("timer.stopped = %v\n", timer.IsStopped)
    29  
    30  	// 证明timer已停
    31  	for globalCount != 10 {
    32  		t0.Sleep(t0.Second)
    33  		globalCount++
    34  	}
    35  }
    36  
    37  func TestTimerParam(t *testing.T) {
    38  	globalCount := 0
    39  	timer := time.NewTimerWithFire(1.5, func(tm *time.Timer) {
    40  		// 这里是运行在协程内的
    41  		globalCount++
    42  		t.Logf("globalCount: %d", globalCount)
    43  	})
    44  	timer.Start()
    45  	t.Logf("timer.stopped = %v\n", timer.IsStopped)
    46  	// 等待timer执行3次
    47  	for globalCount != 3 {
    48  		t0.Sleep(t0.Second)
    49  	}
    50  	// 修改参数
    51  	timer.SetInterval(3)
    52  	timer.SetOnTimer(func(tm *time.Timer) {
    53  		globalCount++
    54  		t.Logf("globalCount2: %d", globalCount)
    55  	})
    56  	// 等待timer执行3次
    57  	for globalCount != 6 {
    58  		t0.Sleep(t0.Second)
    59  	}
    60  	timer.Stop()
    61  }