Go language USES time.After to implement timeout control method in detail

  • 2020-06-15 09:15:46
  • OfStack

preface

Before you start, the time. After use questionable friends can see this article: https: / / www ofstack. com article / 146063. htm

In Golang network programming, we often encounter the need to set timeout, this article will give you a detailed introduction to the Go language using ES15en. After to achieve timeout control related content, the following words are not enough, let's have a look at the detailed introduction.

Scene:

Suppose a business needs to call the service interface A with a timeout of 5 seconds, how do you implement it elegantly and concisely?

We can use select+ ES27en.After approach, 10 points simple applicable implementation.

First of all, let's see time.After() Source:


// 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() said time.Duration After a long time, a channel message of type ES38en.Time is returned. Then, based on this function, the equivalent of implementing the timer, and is non-blocking.

Code implementation of timeout control:


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")
 }
}

We use channel to receive the business return value in the coroutine.

The select statement blocks waiting for channel, which returns the data first, to be received first time.After select will stop blocking and execute the case code. At this point, you have implemented timeout handling for your business code.

conclusion


Related articles: