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的代码。此时就已经实现了对业务代码的超时处理。

原文地址: https://shockerli.net/post/go...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值