I have to execute some statements say every minute. I am not sure which one of the following I should follow. It would be great if someone can explain the pros and cons in terms of memory and CPU.
time.Sleep()
func main() {
go func() {
for {
time.Sleep(time.Minute)
fmt.Println("Hi")
}
}()
time.Sleep(10 * time.Minute) //just to keep main thread running
}
Or Ticker
func main() {
go func() {
for _ = range time.Tick(time.Minute) {
fmt.Println("Hi")
}
}()
time.Sleep(10 * time.Minute) //just to keep main thread running
}
From the docs:
NewTicker returns a new Ticker containing a channel that will send the time with a period specified by the duration argument. It adjusts the intervals or drops ticks to make up for slow receivers. The duration d must be greater than zero; if not, NewTicker will panic. Stop the ticker to release associated resources.
time.Sleep
just waits for the provided time and continues with the program. There is no adjustment if the rest of the code takes longer.
The ticker takes the execution time of the provided block into account and skips an interval, if necessary.
Imagine this scenario: You provide an interval of one minute and your code takes 10 seconds to execute.
In your first version your program executes your code for ten seconds and then sleeps for 60 seconds. Practically it gets called every 70 seconds.
In your second version your code gets executed for 10 seconds, then the ticker adjusts the wait time to 50 seconds. Your code gets executed exactly each minute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With