Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one of the two is idiomatic way? time.Sleep() or ticker?

Tags:

go

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

}
like image 301
drjoenh Avatar asked Nov 15 '18 09:11

drjoenh


1 Answers

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.

like image 187
mbuechmann Avatar answered Nov 13 '22 04:11

mbuechmann