【go】延迟执行和定时器实现

目录

time.Sleep

time.After

time.NewTimer

time.NewTicker


time.Sleep

time.Sleep可以实现延时执行

func TestSleep(t *testing.T) {
	fmt.Println("start time:", time.Now().Format("2006-01-02 15:04:05.000"))

	time.Sleep(2 * time.Second)

	fmt.Println("end   time:", time.Now().Format("2006-01-02 15:04:05.000"))
}

time.After

time.After也可以实现延迟执行。返回一个只读的time.Time类型的channel,读取到的是延迟后的当前时间

func TestAfter(t *testing.T) {
	fmt.Println("start time:", time.Now().Format("2006-01-02 15:04:05.000"))

	var timer <-chan time.Time = time.After(2 * time.Second)
	now := <-timer

	fmt.Println("end   time:", now.Format("2006-01-02 15:04:05.000"))
}

time.NewTimer

time.NewTimer可以实现延迟执行,并且还提供了重置延迟时间的接口实现定时器。timer.C返回的是一个只读的time.Time类型的channel,读取到的是延迟后的当前时间

func TestTimer(t *testing.T) {
	fmt.Println("start time:", time.Now().Format("2006-01-02 15:04:05.000"))

	var timer *time.Timer = time.NewTimer(2 * time.Second)

	for now := range timer.C {
		timer.Reset(3 * time.Second)
		fmt.Println("now   time:", now.Format("2006-01-02 15:04:05.000"))
	}
}

time.NewTicker

time.NewTicker直接实现了定时器。

func TestTicker(t *testing.T) {
	fmt.Println("start time:", time.Now().Format("2006-01-02 15:04:05.000"))

	ticker := time.NewTicker(2 * time.Second)

	for now := range ticker.C {
		fmt.Println("now   time:", now.Format("2006-01-02 15:04:05.000"))
	}
}

你可能感兴趣的:(go,golang,定时器)