4

How to get how long duration set for timeout in context.

example:

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

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

How to get the duration 2*time.Second from within the function f?

1 Answer 1

6

If the func f is called immediately then the time until it times out is the time just set so you can get it by looking at the deadline

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.