当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Go语言利用time.After实现超时控制的方法详解

Go语言利用time.After实现超时控制的方法详解

2018年09月23日  | 移动技术网IT编程  | 我要评论

菊苣,挡板砖,win8怎么升级win10

前言

在开始之前,对time.after使用有疑问的朋友们可以看看这篇文章:

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网