场景:
判断一个“事务”是否超时。
package main
import "time"
func main() {
newChan:=make(chan int,1)
newDelayTimer:=time.NewTimer(time.Duration(time.Second*2))
println("start timer:",time.Now().Format("2006-01-02 15:04:05"))
//newChan<-111
time.Sleep(time.Second*3)
go sendMes(newChan)
select {
case <-newDelayTimer.C:
println("delay!",time.Now().Format("2006-01-02 15:04:05"))
case newMsg:=<-newChan:
println("newMsg chan :",time.Now().Format("2006-01-02 15:04:05"))
println(newMsg)
}
}
func sendMes(newChan chan int){
println("start insert chan :",time.Now().Format("2006-01-02 15:04:05"))
newChan<-222
}
sendMes不适合用在io流中,比如如果想从数据流中读数据然后用超时定时器判断是否超时。不使用time.sleep,go sendMes()会读不到数据,sendMes只执行一次,且很大可能它执行时数据流中还没有数据。