【问题标题】:Getting timeout value from Go's context从 Go 的上下文中获取超时值
【发布时间】:2021-01-19 12:10:45
【问题描述】:

如何在上下文中获取超时设置的持续时间。

示例:

func f(ctx context.Context) {
    // get ctx timeout value
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(),2*time.Second)
    defer cancel()
    f(ctx)
}

如何从函数f中获取持续时间2*time.Second?

【问题讨论】:

    标签: go


    【解决方案1】:

    如果函数 f 被立即调用,那么直到它超时的时间就是刚刚设置的时间,所以你可以通过查看截止日期来获得它

    package main
    
    import (
        "context"
        "fmt"
        "time"
    )
    
    func f(ctx context.Context) {    
             deadline,_:=ctx.Deadline()
             fmt.Println(time.Until(deadline))
        // get ctx timeout value
    }
    
    func main() {
        ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
        defer cancel()
        f(ctx)
    }
    

    https://play.golang.org/p/n3lZJAMdLYs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 2022-12-08
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      • 2014-09-29
      相关资源
      最近更新 更多