15

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

}
1

2 Answers 2

28

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.

Sign up to request clarification or add additional context in comments.

1 Comment

To me it's also significant that the Ticker code is simpler and clearer; it sets up a block of code and indicates it is to be run every (duration). The Sleep code, on the other hand, is less concise and less obvious: it sets up an infinite loop, then at the very end adds a sleep.
1

In the example above there is no difference. But ticker also concurrent safe since it uses channels. For example you can create few workers that should make some job every 2 seconds and you need 1 worker make this work at same time, than you use ticker.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.