Home > Backend Development > Golang > How to use timer Goroutine to perform delayed operations?

How to use timer Goroutine to perform delayed operations?

WBOY
Release: 2024-06-01 22:54:01
Original
362 people have browsed it

Timer Goroutine can be used to perform delayed operations in Go. Create a timer via time.NewTimer() whose C channel receives a signal to indicate the end of the delay. Timers can be stopped with timer.Stop(). The following practical case demonstrates how to use a timer Goroutine to simulate a network request and return a response or timeout after 5 seconds.

如何使用计时器 Goroutine 进行延时操作?

How to use timer Goroutine to perform delay operations

In Go, timer Goroutine can be used to easily implement delay operate. Timer Goroutines provide a non-blocking way to delay program execution.

Using timer Goroutine

To use timer Goroutine, you need to call time.NewTimer(). This function returns a timer type containing a C channel that receives a signal to indicate that the requested delay has elapsed:

package main

import (
    "fmt"
    "time"
)

func main() {
    // 创建一个持续 5 秒的计时器
    timer := time.NewTimer(5 * time.Second)

    // 监听计时器 C 通道中的信号
    <-timer.C
    fmt.Println("5 秒已过")
}
Copy after login

Stop timer

If desired, you can stop the timer before it expires. Call the timer.Stop() method to cancel the timer:

timer.Stop()
Copy after login

Practical case

The following is a practical example of using timer Goroutine to simulate network requests Case:

package main

import (
    "fmt"
    "net/http"
    "time"
)

func main() {
    // 模拟发送网络请求
    request := func() (resp *http.Response, err error) {
        // 假装向网络发送请求并等待 5 秒
        timer := time.NewTimer(5 * time.Second)
        defer timer.Stop()
        select {
        case <-timer.C:
            resp = &http.Response{}
        }
        return resp, nil
    }

    // 使用计时器 Goroutine发送请求
    resp, err := request()
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(resp)
}
Copy after login

The above is the detailed content of How to use timer Goroutine to perform delayed operations?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template