在Go中,我想要time.Sleep
一段时间(例如在重试之间等待),但是如果上下文被取消(不仅仅是从截止日期,而且还是手动),想要快速返回。
这样做的最佳方式是什么?谢谢!
您可以使用select
来实现此目的:
package main
import (
"fmt"
"time"
"context"
)
func main() {
fmt.Println("Hello, playground")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func(){
t := time.Now()
select{
case <-ctx.Done(): //context cancelled
case <-time.After(2 * time.Second): //timeout
}
fmt.Printf("here after: %v\n", time.Since(t))
}()
cancel() //cancel manually, comment out to see timeout kick in
time.Sleep(3 * time.Second)
fmt.Println("done")
}
我设法通过将CancelContext与TimeoutContext结合起来做类似的事情......
以下是示例代码:
cancelCtx, cancel := context.WithCancel(context.Background())
defer cancel()
// The program "sleeps" for 5 seconds.
timeoutCtx, _ := context.WithTimeout(cancelCtx, 5*time.Second)
select {
case <-timeoutCtx.Done():
if cancelCtx.Err() != nil {
log.Printf("Context cancelled")
}
}
在this repo中,您可以找到上述代码的完整用法。对不起我的简短回答,我还没有打开电脑,并且通过电话回答并不容易......