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)
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.