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

作者:格物 时间:2024-04-26 17:21:50 

前言

在开始之前,对time.After使用有疑问的朋友们可以看看这篇文章:https://www.aspxhome.com/article/146063.htm

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

来源:https://shockerli.net/post/golang-select-time-implement-timeout/

标签:golang,超时,time.after
0
投稿

猜你喜欢

  • JavaScript初级教程(第五课续)第1/3页

    2024-04-17 10:10:07
  • python开发一款翻译工具

    2022-01-19 07:28:43
  • 对python中Json与object转化的方法详解

    2022-11-13 23:42:35
  • Win2008中安装的MSSQL2005后无法访问的解决方法

    2024-01-21 03:57:57
  • Python 发送SMTP邮件的简单教程

    2021-04-27 00:26:51
  • javascript判断中文的正则

    2024-04-10 10:56:27
  • Vue中的常用指令及用法总结

    2024-06-07 16:05:31
  • django.db.utils.ProgrammingError: (1146, u“Table‘’ doesn’t exist”)问题的解决

    2022-01-12 14:02:31
  • Golang爬虫框架 colly的使用

    2024-02-02 13:40:55
  • MYSQL教程:索引和查询优化程序

    2009-02-27 15:52:00
  • 用Python编写简单的微博爬虫

    2022-10-07 04:58:34
  • instanceof 内部机制探析

    2009-09-25 13:09:00
  • 一文带你熟悉Go语言中函数的使用

    2023-07-13 08:22:23
  • 微信小程序设置http请求的步骤详解

    2023-11-12 18:04:10
  • Pandas使用Merge与Join和Concat分别进行合并数据效率对比分析

    2023-03-13 12:14:01
  • PHP设计模式中的命令模式

    2023-05-27 21:13:43
  • 在漏洞利用Python代码真的很爽

    2023-11-24 15:57:29
  • 安装SQL Server2019详细教程(推荐!)

    2024-01-22 18:23:11
  • 基于wxPython的GUI实现输入对话框(1)

    2023-01-07 19:54:21
  • Ubuntu 设置开放 MySQL 服务远程访问教程

    2024-01-29 07:45:39
  • asp之家 网络编程 m.aspxhome.com