time.Alfter的坑

Posted StaticAuto

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了time.Alfter的坑相关的知识,希望对你有一定的参考价值。

作为超时机制的首选,time.Alfter的使用非常的简单

select 
	case <-chanan:
		fmt.Println("now!!!")
		return
	case <-time.After(time.Duration(3 * time.Second)):
		fmt.Println("timeout!!!")
		return
	

但是!!!!!!!
Timer 不会被 GC 回收直到它被触发,如果需要考虑效率的话,Timer 不再被需要时,需要主动调用 Timer.Stop。

在开头位置加上defer timer.Stop(),在测试中可以明显的看出效率高了许多,有兴趣的读者可以自己使用go test体验

以上是关于time.Alfter的坑的主要内容,如果未能解决你的问题,请参考以下文章