文章目录
本文参考:
超时Timesout
import "time"
包后,其中的两个方法:
// 将当前的goroutine暂停d的时间,在暂停结束后继续执行
func Sleep(d Duration)
// 返回一个 <-chan Time类型的只读管道,在等待d时间以后,将当前时间放入管道
func After(d Duration) <-chan Time {
return NewTimer(d).C
}
time.After(d)立即返回一个 <-chan Time类型的只读管道,不阻塞,继续执行,在等待时间d以后,才将当前时间放入管道。
package main
import (
"time"
"fmt"
)
func main() {
tchan := time.After(time.Second*3)
fmt.Printf("tchan type=%T\n",tchan)
fmt.Println("mark 1") //立即输出
fmt.Println("tchan=",<-tchan) //等待3s输出
fmt.Println("mark 2")
}
输出:
tchan type=<-chan time.Time
mark 1
tchan= 2022-11-01 13:22:03.406472 +0800 HKT m=+3.001218459
mark 2
将上面两个函数结合起来用于超时控制的场景:
package main
import (
"fmt"
"time"
)
func main() {
c1 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c1 <- "result 1" //Sleep 2s 往管道c1中写数据
}()
select { // 超时了
case res := <-c1:
fmt.Println(res)
case <-time.After(1 * time.Second): // select 1s 超时
fmt.Println("timeout 1")
}
c2 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second) //Sleep 2s 往管道c2中写数据
c2 <- "result 2"
}()
select { // 顺利打印出结果
case res := <-c2:
fmt.Println(res) // select 不超时3s内打印出结果
case <-time.After(3 * time.Second):
fmt.Println("timeout 2")
}
}
输出:
timeout 1
result 2