Home  >  Article  >  Backend Development  >  golang set timeout

golang set timeout

王林
王林Original
2023-05-16 14:32:382172browse

Golang is an efficient programming language that is widely used in development in various fields. In some specific scenarios, we need to set a timeout to avoid deadlock or stuck in the program. In this article, I will introduce in detail how Golang sets timeout, and several ways to set timeout.

1. Use channel

In Golang, you can use channel to implement the timeout function. We can define a channel with a timeout parameter and retrieve the data according to the timeout time after the program is executed.

For example, the following is a simple sample code:

package main

import (
    "fmt"
    "time"
)

func main() {
    ch := make(chan string, 1)

    go func() {
        time.Sleep(time.Second * 3)
        ch <- "task completed"
    }()

    select {
    case res := <-ch:
        fmt.Println(res)
    case <-time.After(time.Second * 2):
        fmt.Println("timeout")
    }
}

We can see that a channel with a timeout parameter is created. After the program is executed, a concurrent coroutine will be opened. It takes 3 seconds for the process to perform the task. In the select statement, we listen to two channels. If the data is received within the timeout time, that is, the task execution is completed, the program will print out "task completed". If no data is received within the timeout period, the program will print out "timeout".

2. Using context

In Golang, the context package provides a method for passing request range data, cancellation signals, and timeouts. We can use the WithTimeout function to create a Context object carrying a timeout.

For example, the following is a simple sample code:

package main

import (
    "context"
    "fmt"
    "time"
)

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

    go func(ctx context.Context) {
        time.Sleep(time.Second * 3)
        select {
        case <-ctx.Done():
            fmt.Println(ctx.Err())
        default:
            fmt.Println("task completed")
        }
    }(ctx)

    select {
    case <-ctx.Done():
        fmt.Println(ctx.Err())
    }
}

In this example, we use the WithTimeout function to create a Context object with a timeout of 2 seconds. In the enabled concurrent coroutine, we block and wait for 2 seconds. If the task is completed within 2 seconds, the coroutine will print out "task completed", otherwise it will print out a context timeout error message. In the select statement, we listen to the Done() channel of the Context object. If the Done() channel signal is received, the program will cancel the task and output an error message.

3. Use cancel

In some specific cases, we may need to cancel the execution of a task by setting the cancel function. For example, in a scenario where data is requested from the network, a timeout may be set. If no data is requested within the timeout, we need to cancel the request.

For example, the following is a simple sample code:

package main

import (
    "context"
    "fmt"
    "time"
)

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

    ch := make(chan string, 1)

    go func(ctx context.Context) {
        time.Sleep(time.Second * 3)
        ch <- "task completed"
    }(ctx)

    select {
    case res := <-ch:
        fmt.Println(res)
    case <-ctx.Done():
        fmt.Println(ctx.Err())
    }

    cancel()
}

In this example, we create a Context object carrying a timeout and start a concurrent coroutine to execute the task. In the select statement, we monitor the Done() channel of the task and Context objects. If the task is completed, "task completed" will be output, otherwise a timeout error message will be output. Call the cancel() function at the end of the program to cancel task execution. If the task is completed within the timeout period, the program will exit normally. Otherwise, the program will be blocked in the select statement until the cancel() function is executed.

4. Using deadline

In addition to using the WithTimeout function, the context package also provides another way to time out, that is, using the WithDeadline function. Unlike the WithTimeout function, the parameter of the WithDeadline function is a deadline, not a timeout. When the task is completed before the deadline, the program will exit normally.

For example, the following is a simple sample code:

package main

import (
    "context"
    "fmt"
    "time"
)

func main() {
    ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*2))
    defer cancel()

    go func(ctx context.Context) {
        time.Sleep(time.Second * 3)
        select {
        case <-ctx.Done():
            fmt.Println(ctx.Err())
        default:
            fmt.Println("task completed")
        }
    }(ctx)

    select {
    case <-ctx.Done():
        fmt.Println(ctx.Err())
    }
}

In this example, we use the WithDeadline function to create a Context object with a deadline of 2 seconds. If the task is completed before the deadline, the program will output "task completed", otherwise it will output a timeout error message. In the select statement, we also listen to the Done() channel of the Context object. If a signal from the Done() channel is received, the program will output an error message.

Summary:

Golang provides a variety of ways to set timeouts. By using methods such as channel, context, cancel, and deadline, we can avoid program deadlock or stuck problems and ensure the efficiency and stability of program operation. In actual development, according to different needs and scenarios, we can choose the appropriate method to set the timeout.

The above is the detailed content of golang set timeout. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:golang view methodNext article:golang view method