前言
在開始之前,對time.After使用有疑問的朋友們可以看看這篇文章:https://www.jb51.net/article/146063.htm
我們在Golang網絡編程中,經常要遇到設置超時的需求,本文就來給大家詳細介紹了Go語言利用time.After實現超時控制的相關內容,下面話不多說了,來一起看看詳細的介紹吧。
場景:
假設業務中需調用服務接口A,要求超時時間為5秒,那么如何優雅、簡潔的實現呢?
我們可以采用select+time.After的方式,十分簡單適用的實現。
首先,我們先看time.After()
源碼:
// After waits for the duration to elapse and then sends the current time
// on the returned channel.
// It is equivalent to NewTimer(d).C.
// The underlying Timer is not recovered by the garbage collector
// until the timer fires. If efficiency is a concern, use NewTimer
// instead and call Timer.Stop if the timer is no longer needed.
func After(d Duration) -chan Time {
return NewTimer(d).C
}
time.After()
表示time.Duration
長的時候后返回一條time.Time類型的通道消息。那么,基于這個函數,就相當于實現了定時器,且是無阻塞的。
超時控制的代碼實現:
package main
import (
"time"
"fmt"
)
func main() {
ch := make(chan string)
go func() {
time.Sleep(time.Second * 2)
ch - "result"
}()
select {
case res := -ch:
fmt.Println(res)
case -time.After(time.Second * 1):
fmt.Println("timeout")
}
}
我們使用channel來接收協程里的業務返回值。
select語句阻塞等待最先返回數據的channel,當先接收到time.After
的通道數據時,select則會停止阻塞并執行該case的代碼。此時就已經實現了對業務代碼的超時處理。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
您可能感興趣的文章:- 詳解Golang 中的并發限制與超時控制
- 一文搞懂如何實現Go 超時控制