Go takes time. After implementation timeout control

Source: Internet
Author: User
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.

selectWhen 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
...
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.