How to implement timers in go language: timers can be implemented through time.sleep, time.after and time.Timer, such as [time.Sleep(time.Second)].
The operating environment of this article: windows10 system, Go 1.11.2, thinkpad t480 computer.
1. Creation of timer
There are three ways to implement timers in golang, namely time.sleep, time.after, time.Timer
Among them time.after and time. Timer needs to release the channel to achieve the timing effect
package mainimport ( "fmt" "time")func main() { /* 用sleep实现定时器 */ fmt.Println(time.Now()) time.Sleep(time.Second) fmt.Println(time.Now()) /* 用timer实现定时器 */ timer := time.NewTimer(time.Second) fmt.Println(<-timer.C) /* 用after实现定时器 */ fmt.Println(<-time.After(time.Second)) }
2. Reset and stop the timer
Reset the timer timer.Reset(d Duration)
Stop the timer timer.Stop()
3. Implementation of periodic timing Tiker
Using Tiker in golang can achieve the effect of periodic timing
package main import ( "fmt" "time") func main() { tiker := time.NewTicker(time.Second) for i := 0; i < 3; i++ { fmt.Println(<-tiker.C) } }
Related recommendations: golang tutorial
The above is the detailed content of What is the method to implement timer in go language. For more information, please follow other related articles on the PHP Chinese website!