创建定时器
func main(){
timer:=time.NewTimer(time.Second*2)
expirationTime:=<-timer.C
if timer.stop==false{
fmt.Println("stoped!
")
}
}
使用select实现超时机制
func main() {
intChan:=make(chan int,1)
go func(){
time.Sleep(time.Second)
intChan<-1
}()
select {
case e:=<-intChan:
fmt.Println("Receive : %v \n",e)
case <-time.After(time.Millisecond*500):
fmt.Println("timeout!")
}
}
for实现超时机制
func main() {
intChan:=make(chan int,1)
go func(){
for i:=0;i<5;i++{
time.Sleep(time.Second)
intChan<-i
}
close(intChan)
}()
timeout:=time.Millisecond*500
var timer *time.Timer
for{
if timer==nil{
timer=time.NewTimer(timeout)
}else{
timer.Reset(timeout)
}
select{
case e,ok:=<-intChan:
if !ok{
fmt.Println("end")
return
}
fmt.Printf("Received: %v\n",e)
case <-timer.C:
fmt.Println("Timeout!")
}
}
}