This is a creation in Article, where the information may have evolved or changed.
Scene:
Assuming that service interface A is called in the business, requiring a time-out of 5 seconds, how elegant and concise is the implementation?
We can adopt the select
+ time.After
way, very simple to apply the implementation.
First, let's look at the time.After()
source code first:
// 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()
Represents time.Duration
a time.Time
type of channel message that is returned after a long time. Then, based on this function, it is equivalent to implementing a timer, and is non-blocking.
Code implementations for timeout control:
package mainimport ( "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 it channel
to receive the business return value of the coprocessor thread.
select
When a statement blocks waiting for the data to be returned first channel
, yourselves receives time.After
the channel data, it select
stops blocking and executes the case
code. The time-out processing of the business code has been implemented.
Original address: Https://shockerli.net/post/go
...