Golang 小技巧:使用 context.WithTimeout 控制任务超时
【摘要】 在 Go 中调用数据库、HTTP 接口或者执行耗时任务时,最好给操作设置一个超时时间,避免任务一直阻塞。可以使用 context.WithTimeout:ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)defer cancel()然后把 ctx 传给后续任务:select {case <-time....
在 Go 中调用数据库、HTTP 接口或者执行耗时任务时,最好给操作设置一个超时时间,避免任务一直阻塞。
可以使用 context.WithTimeout:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
然后把 ctx 传给后续任务:
select {
case <-time.After(3 * time.Second):
fmt.Println("任务完成")
case <-ctx.Done():
fmt.Println("任务超时:", ctx.Err())
}
因为超时时间设置为 2 秒,而任务需要 3 秒,所以最终会进入:
任务超时: context deadline exceeded
为什么要 defer cancel()
即使任务提前完成,也建议调用 cancel(),这样可以及时释放相关资源。
常见写法就是:
ctx, cancel := context.WithTimeout(parentCtx, 2*time.Second)
defer cancel()
小结
context.WithTimeout 很适合用在:
- HTTP 请求
- 数据库查询
- RPC 调用
- 耗时任务控制
给外部调用加上超时限制,可以避免某个任务长时间卡住整个业务流程。
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)