gpt4 book ai didi

go - 如何在响应式上下文取消的情况下休眠?

转载 作者:IT王子 更新时间:2023-10-29 01:25:41 26 4
gpt4 key购买 nike

在 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")

}

这是 Go-playground link

关于go - 如何在响应式上下文取消的情况下休眠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55135239/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com