如何通过响应式上下文取消来睡觉?

问题描述 投票:2回答:2

在Go中,我想要time.Sleep一段时间(例如在重试之间等待),但是如果上下文被取消(不仅仅是从截止日期,而且还是手动),想要快速返回。

这样做的最佳方式是什么?谢谢!

go
2个回答
5
投票

您可以使用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


0
投票

我设法通过将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中,您可以找到上述代码的完整用法。对不起我的简短回答,我还没有打开电脑,并且通过电话回答并不容易......

© www.soinside.com 2019 - 2024. All rights reserved.