Home >Backend Development >Golang >How to detect when a timeout occurs using Go's WithTimeout

How to detect when a timeout occurs using Go's WithTimeout

WBOY
WBOYforward
2024-02-09 11:00:18663browse

如何使用 Go 的 WithTimeout 检测超时发生

In this article, php editor Xinyi will introduce you how to use the WithTimeout function in the Go language to detect the occurrence of timeout. The WithTimeout function is a function in the Go language standard library. It can be used to set a timeout. When an operation is not completed within the specified time, this function can be used to determine whether a timeout occurs. By rationally using the WithTimeout function, we can avoid long-term waiting or blocking of the program and improve the performance and stability of the program. Next, we will introduce in detail the usage and precautions of the WithTimeout function to help you better master the skills of handling timeout issues in the Go language.

Question content

I have the following go code:

func MyFunc(ctx context.Context, cfg *Config) (packedevent []byte, err error, publishEvent bool) {
    var cancel context.CancelFunc
    ctx, cancel = context.WithTimeout(ctx, cfg.ScanTimeout)
    defer cancel()

    event := GetEvent(ctx, cfg)
    packedevent, err = PackEvent(event)

    publishEvent = shouldSendToIoT(event)

    return
}

I tried to timeout the function using context.withtimeout.

What I haven't been able to figure out is how to set err if a timeout occurs.

I looked at the examples in the go documentation but I don't really understand it. <-ctx.done() Does the condition always mean that the timeout has been reached? This example seems to illustrate the opposite - <-ctx.done() means the code runs to completion without a timeout.

I'm looking for instructions on how to detect if code running using context.withtimeout has timed out.

Additionally, I would like to understand where in the code I should check if a timeout occurs. My first thought was to put this check at the end of the function, but would it be too late to check?

Solution

To detect whether the context has timed out, check ctx.error(). If the error is context.canceled, the context has been canceled using the cancel() function. If it is context.deadlineexceeded, then it times out.

To check if the context has been canceled or timed out, use:

select {
   case <-ctx.Done():
       // canceled or timed out
   default:
       // So the select will not block
}

The above is the detailed content of How to detect when a timeout occurs using Go's WithTimeout. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete