Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sleep in Go?

How can I sleep for a variable duration using Go’s time.Sleep(d Duration)-function?

In all tutorials, How-To’s, etc. I just saw how people are using constant durations, such as time.sleep(3 * time.Second) (like here)

The only pattern I keep seeing is the one for decrementing an additional counter within a loop, such as (from here)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if s <= 0 {
    break
} else {
    fmt.Println(s)
    time.Sleep(1 * time.Second)  // wait 1 sec
    s--                          // reduce time
}

Is this really the only way to do it – using such a verbose boilerplate for such a simple task?

Is there really no support for simply writing time.Sleep(sec) or time.Sleep(sec * time.Duration) if sec holds a number value?

This seems so 1970’s-like ….

>Solution :

Duration is just a newtype’d int64, storing a nanoseconds count. All the multiplicative constants do is the scale from nanosecond to the specified time unit.

All you need to do is convert your runtime integer value to a Duration, then scale it to whatever your unit is:

time.Sleep(time.Duration(thing) * time.Second)

Because numeric constants are untyped, they will automatically instantiate whatever type is expected as long as that type has a numeric underlying representation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading