如何在Go中延长上下文的超时时间? [英] How can I extend the timeout of a context in Go?

查看:134
本文介绍了如何在Go中延长上下文的超时时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,创建上下文时的超时时间为10秒.过了一会儿(例如2秒后),我想将其刷新到此时间后的10秒.

For example, the context is created with timeout to be 10 seconds later. After a while (e.g. 2 seconds later), I want to refresh it to be 10 seconds later from this time.

我该怎么办?

推荐答案

context.Context 并不是这样设计的. context.Context 被委派给工作人员,如果工作人员发现应该允许更多的时间,则它不能覆盖主叫方".

context.Context is not designed that way. context.Context is delegated down to workers, and if a worker finds that more time should be allowed, it can't override the "master's call".

如果您遇到的情况是要使用最初的10秒钟超时,但是这10秒钟不是一成不变的(例如,它可能会在过期之前更改),那么请不要使用具有10秒钟超时的上下文.而是使用带有取消功能的上下文: context.WithCancel() ,并自行管理10秒超时(例如,使用 time.AfterFunc() 或带有 time.Timer ).如果超时已到期,并且您(或您的员工)未检测到应延长的时间,请调用cancel函数.

If you have a situation where an initial 10 seconds timeout is to be used, but this 10 seconds is not written in stone (e.g. it may change before it expires), then don't use a context with 10 seconds timeout. Instead use a context with a cancel function: context.WithCancel(), and manage the 10 seconds timeout yourself (e.g. with time.AfterFunc() or with a time.Timer). If the timeout has expired and you (or your workers) did not detect that it should be extended, call the cancel function.

如果您在超时之前检测到超时应延长,请重置计时器,并且不要使用取消功能取消上下文.

If before the deadline you detect the timeout should be extended, reset the timer and do not cancel the context with the cancel function.

这篇关于如何在Go中延长上下文的超时时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆