业务逻辑中,对一些逻辑进行合理的超时控制,往往能够极大的提升程序的稳定性,特别是对一些接口的实现上。
go语言中,通过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类型的通道消息,但是在取出channel内容之前不阻塞,后续程序可以继续执行。
特性样例
func TestOther(t *testing.T) {
t.Log(time.Now().Unix())
tm := time.After(3 * time.Second)
t.Log("waiting...")
t.Log(<-tm)
t.Log(time.Now().Unix())
}
输出:

可以看到,调用time.After()后,程序非阻塞,继续执行,知道读取tm管道信息时,阻塞3s后,才读取到管道信息
超时控制
func waitForStopOrTimeOut(stopCh <- chan struct{}, timeout time.Duration) <- chan bool {
stopWithTimeOut := make(chan bool)
go func() {
select {
case <- stopCh:
// 若接收到业务逻辑正常结束的消息,则为自然结束
fmt.Println("自然结束")
stopWithTimeOut <- false
case <- time.After(timeout):
// 若timeout时间内,未接收到业务逻辑正常结束的消息,则为超时
// timeout时间后,time.After(timeout)可读取到管道信息
fmt.Println("超时")
stopWithTimeOut <- true
}
close(stopWithTimeOut)
}()
return stopWithTimeOut
}
func doSomething() {
time.Sleep(time.Second * 2)
}
func TestOther(t *testing.T) {
t.Log("start")
stopCh := make(chan struct{})
go func() {
// 需要控制超时时间的业务逻辑
doSomething()
// 业务逻辑正常执行完,通知管道stopCh,执行完成
stopCh <- struct {}{}
}()
// 启用超时控制
stopWithTimeOut := waitForStopOrTimeOut(stopCh, 3 * time.Second)
select {
// 若为超时,正常结束,isTimeOut=false, 否则为true
case isTimeOut := <- stopWithTimeOut:
if isTimeOut {
t.Log("end timeout")
} else {
t.Log("end ok")
}
}
return
}
上述代码,限制的超时时间是3s, waitForStopOrTimeOut(stopCh, 3 * time.Second), doSomething()中,time.Sleep()分别为2s, 4s时的执行结果分别为:


可见,我们已经实现了符合预期的超时控制逻辑。
精选应用推荐
安全便捷的密码管理工具
安全加密
跨设备同步
一键填充
免费使用
云幻梦密码本 - 安全密码管理
云幻梦密码本是一款专业级密码管理工具,采用银行级加密技术保护您的所有密码和个人信息。支持跨设备同步、一键自动填充、安全密码生成和生物识别登录等功能,让您的数字生活更加安全便捷。
选择平台下载
资源搜索推荐
一站式资源搜索平台
资源搜索
多源聚合
免费使用
无广告
千搜123 | 资源搜索
智能搜索
多类资源
快速响应
安全访问
千搜123是一个强大的资源搜索网站,聚合了多种资源搜索引擎,提供文档、软件、影视、音乐、学习资料等多种资源的快速搜索服务。界面简洁无广告,搜索结果精准,是您寻找各类资源的得力助手。
- 聚合多个优质资源搜索引擎,一站式搜索
- 支持文档、软件、影视、学习资料等多种资源类型
- 界面简洁,无干扰广告,专注搜索体验
- 搜索结果快速准确,节省您的时间


