作为超时机制的首选,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体验