Go Wiki: 超時與截止時間
要放棄執行過長的同步呼叫,請使用帶 time.After 的 select 語句
import "time"
c := make(chan error, 1)
go func() { c <- client.Call("Service.Method", args, &reply) } ()
select {
case err := <-c:
// use err and reply
case <-time.After(timeoutNanoseconds):
// call timed out
}
請注意,通道 c 的緩衝區大小為 1。如果它是一個無緩衝通道,並且 client.Call 方法的執行時間超過 timeoutNanoseconds,那麼通道傳送將會永遠阻塞,goroutine 也將永遠不會被銷燬。
參考
time.After: https://pkg.go.dev/time/#After
select: https://golang.com.tw/ref/spec#Select_statements
部落格文章: https://golang.com.tw/blog/2010/09/go-concurrency-patterns-timing-out-and.html
此內容是 Go Wiki 的一部分。