go语言 timer.reset分析

官方API定义

func (t *Timer) Reset(d Duration) bool
Reset使t重新开始计时,(本方法返回后再)等待时间段d过去后到期。如果调用时t还在等待中会返回真;如果t已经到期或者被停止了会返回假。

注:比如你的定时器设置的是3秒,中间sleep1秒 < 3,这时候如果reset的话返回的就是 true(因为定时器还在等待),如果你sleep4秒 > 3,那么返回的就是false

案例解析

/*
1.
*/
func test1(){
	start := time.Now()
	fmt.Println("startTime:------",start)
	timer := time.AfterFunc(2*time.Second, func() {
		fmt.Println("after func callback, elaspe:", time.Now())
	})

	time.Sleep(1 * time.Second)
	// time.Sleep(3*time.Second)
	// Reset 在 Timer 还未触发时返回 true;触发了或 Stop 了,返回 false
	if timer.Reset(4 * time.Second) {
		fmt.Println("timer has not trigger!-----",time.Now())
	} else {
		fmt.Println("timer had expired or stop!----",time.Now())
	}

	// 保证上面的计时器时间到了能继续执行,不然会直接跳出这个函数,无法执行timer.after
	time.Sleep(10 * time.Second)
	fmt.Printf("end:-------",time.Now())
}

startTime:------ 2020-07-22 14:41:00.469027 +0800 CST m=+0.000100730
timer has not trigger!----- 2020-07-22 14:41:01.474315 +0800 CST m=+1.005385095
after func callback, elaspe: 2020-07-22 14:41:05.477855 +0800 CST m=+5.008908154
end:-------%!(EXTRA time.Time=2020-07-22 14:41:11.478856 +0800 CST m=+11.009885047)
timer.reset直接会重置定时器的after的触发时间。

func test2(){
	start := time.Now()
	fmt.Println("startTime:------",start)
	timer := time.AfterFunc(2*time.Second, func() {
		//fmt.Println("after func callback, elaspe:", time.Now().Sub(start))
		fmt.Println("after func callback, elaspe:", time.Now())
	})

	time.Sleep(3 * time.Second)
	if timer.Reset(4 * time.Second) {
		fmt.Println("timer has not trigger!-----",time.Now())
	} else {
		fmt.Println("timer had expired or stop!----",time.Now())
	}
	// 保证上面的计时器时间到了能继续执行,不然会直接跳出这个函数,无法执行timer.after
	time.Sleep(10 * time.Second)
	fmt.Printf("end:-------",time.Now())
}

startTime:------ 2020-07-22 15:00:06.719613 +0800 CST m=+0.000102610
after func callback, elaspe: 2020-07-22 15:00:08.72458 +0800 CST m=+2.005061129
timer had expired or stop!---- 2020-07-22 15:00:09.723649 +0800 CST m=+3.004125593
after func callback, elaspe: 2020-07-22 15:00:13.725859 +0800 CST m=+7.006319244
end:-------%!(EXTRA time.Time=2020-07-22 15:00:19.727676 +0800 CST m=+13.008110925)
这个案例就是验证了一下reset的返回值,先调用after,然后睡了3秒,所以直接返回了false,然后重置定时器为4秒,4秒后再调用after

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mindcarver

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值