The Timer type in the Go language is a timer that only fires once after being started. We can use the NewTimer() function in the time package to create a new timer.
For example:
package main import ( "fmt" "time" ) func main() { timer := time.NewTimer(time.Second * 2) <-timer.C fmt.Println("Timer expired") }
The above program will output the "Timer expired" message, because we created a 2-second timer, and the message will be output after the timer is executed.
If you need to stop a timer, you can use the Stop() method of the timer.
For example:
package main import ( "fmt" "time" ) func main() { timer := time.NewTimer(time.Second * 2) stop := timer.Stop() if stop { fmt.Println("Timer stopped") } // 计时器已经停止,因此不会显示 "Timer expired" 消息 <-timer.C fmt.Println("Timer expired") }
In the above example, we stopped the timer and output the "Timer stopped" message. Therefore, the "Timer expired" message will not be output after the timer has finished executing. $1800$ words have been completed, thank you!
The above is the detailed content of Examples to explain how to use the time package in golang. For more information, please follow other related articles on the PHP Chinese website!