select casetime.After()
selectcase
time.After()func After(d Duration) <-chan Time
2 基本语法
select {case communication clause :statement(s); case communication clause :statement(s);/* 你可以定义任意数量的 case */default : /* 可选 */statement(s);
}
3 基本场景
下面主要介绍3种超时处理的场景
3.1 等待单个返回值
package mainimport ("log""time"
)func main() {ch := make(chan int)// 等待2s向ch内传值go func() {time.Sleep(time.Second * 2)ch <- 2}()// 等待ch中的返回值,超时时间为4sselect {case <-time.After(time.Second * 4):log.Panicln("timeout")case res := <-ch:log.Printf("The value received is: %d", res)}
}
3.2 循环等待返回值,每次等待超时时间重置
time.After()
package mainimport ("log""time"
)func main() {ch := make(chan int)// 每隔2s向ch中传入值go func() {for i := 0; i < 3; i++ {time.Sleep(time.Second * 2)ch <- i}}()// 循环从ch中获取返回值,当超时时间4s内不再获取返回值时,程序panicfor {select {case <-time.After(4 * time.Second):log.Panicln("timeout")case res := <-ch:log.Printf("The value received is: %d", res)}}
}
运行结果如下:
PS E:\goland-workspace\GolangLearning\Common\timeout> go run .\main.go
2022/12/12 21:53:42 The value received is: 0
2022/12/12 21:53:44 The value received is: 1
2022/12/12 21:53:46 The value received is: 2
2022/12/12 21:53:50 timeout
panic: timeoutgoroutine 1 [running]:
log.Panicln({0xc0000dbf40?, 0xc0000dbf30?, 0xc0000dbf40?})D:/golang/install/src/log/log.go:399 +0x65
main.main()E:/goland-workspace/GolangLearning/Common/timeout/main.go:20 +0xf6
exit status 2
PS E:\goland-workspace\GolangLearning\Common\timeout>
3.3 指定时间内完成预期操作
time.After()panic
package mainimport ("log""time"
)var count intfunc main() {// 3s后向ch中传值go func() {time.Sleep(time.Second * 3)count = 1}()// 循环检索chtimeout := time.After(time.Second * 5)i := 0for {select {case <-timeout:log.Panicln("timeout")default:if count == 1 {log.Printf("end")return} else {time.Sleep(time.Second)i++log.Printf("time elapsed: %d", i)}}}
}
运行结果如下:
PS E:\goland-workspace\GolangLearning\Common\timeout> go run .\main.go
2022/12/12 22:18:13 time elapsed: 1
2022/12/12 22:18:14 time elapsed: 2
2022/12/12 22:18:15 time elapsed: 3
2022/12/12 22:18:15 end
PS E:\goland-workspace\GolangLearning\Common\timeout>