Sobes.tech
Junior — Middle

Kuidas rakendada operatsiooni täitmise aja piirangut kasutades context.WithTimeout Go keeles?

sobes.tech AI

Vastus AI-lt

In the Go language, a context with a timeout is often used to limit the execution time of an operation via the context.WithTimeout function. This returns a new context and a cancellation function. If the operation does not complete before the timeout expires, the context is automatically canceled.

Example of usage:

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

select {
case result := <-someLongRunningOperation(ctx):
    fmt.Println("Operation finished:", result)
case <-ctx.Done():
    fmt.Println("Timeout exceeded:", ctx.Err())
}

Here, someLongRunningOperation should accept ctx and periodically check ctx.Done() for proper interruption. This allows safely canceling the operation in case of timeout.