is a very practical function that returns a one-way channel (<-chan) for reading, which sends the current time after a specified time interval. This mechanism is often used to implement timeout control and delayed execution scenarios.
Application scenarios:
1. Delayed execution and timing tasks
package main import ( "fmt" "time" ) func main() { // Wait for 3 seconds timer := (3 * ) // Blocking waiting channel sending time x := <-timer (x) // When the above <-timer is executed, it means that you have waited for 5 seconds ("3 seconds have passed") // You can continue to execute your logic...}
2. Timeout control
It is also commonly used to implement timeout control. For example, when you send an HTTP request, you may not want the request to wait for the response without limit, but rather want to stop waiting after a certain timeout time and process the timeout logic:
Timeout control should be a very common use scenario.
package main import ( "fmt" "io/ioutil" "net/http" "time" ) func main() { client := &{ Timeout: 10 * , // Set the client timeout time } // Simulate a request that may timeout resp, err := ("/may-timeout") if err != nil { ("Request Error:", err) return } defer () // Use the timeout to read the response body done := make(chan bool, 1) go func() { // Simulate the read response body, which may actually be () // Use simulation to consume time (2 * ) done <- true }() select { case <-done: // Read successfully body, _ := () ("Reading the response body successfully:", string(body)) case <-(1 * ): // time out ("Read response body timeout") } }
Timeout control channel combines select.
go timer example
package main import ( "fmt" "time" ) // Define the stop function, accept deviceid and gunid as parametersfunc stop(deviceid int, gunid int) { ("Stopping with device ID: %d and gun ID: %d\n", deviceid, gunid) } func main() { // Set the parameters to be passed to the stop function deviceid := 1 gunid := 2 // Use goroutine to execute timer asynchronously go func() { // Create a channel that will close after 10 seconds timer := (10 * ) // Wait for the channel to close, that is, wait for 10 seconds <-timer // Execute the stop function after 10 seconds stop(deviceid, gunid) }() // The main program can continue to perform other tasks ("Main program continues to run...") // For demonstration, let the main program run for a period of time so as to observe the execution of the stop function (15 * ) ("Main program ends.") }
The difference between
What's the difference?
-
Simple and direct.
-
Return to the channel, blocking when reading the channel.
This is the end of this article about the role of go language(). For more related go language() content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!