31

I am trying to implement random time sleep (in Golang)

r := rand.Intn(10)
time.Sleep(100 * time.Millisecond)  //working 
time.Sleep(r * time.Microsecond)    // Not working (mismatched types int and time.Duration)
Ravichandra
  • 2,162
  • 4
  • 24
  • 36
  • 1
    Related: [conversion of time.Duration type microseconds value to milliseconds in golang](https://stackoverflow.com/questions/41503758/conversion-of-time-duration-type-microseconds-value-to-milliseconds-in-golang/41503910#41503910). – icza Jun 14 '17 at 08:16
  • [How to multiply duration by integer?](https://stackoverflow.com/q/17573190/86967) – Brent Bradburn Sep 11 '19 at 08:15

2 Answers2

57

Match the types of argument to time.Sleep:

r := rand.Intn(10)
time.Sleep(time.Duration(r) * time.Microsecond)

This works because time.Duration has int64 as its underlying type:

type Duration int64

Docs: https://golang.org/pkg/time/#Duration

Cirelli94
  • 1,714
  • 1
  • 15
  • 24
abhink
  • 8,740
  • 1
  • 36
  • 48
  • int64 or uint64 ? – Dmytro Bogatov Sep 20 '18 at 03:25
  • `time.Sleep((rand.Int63n(10)) * time.Second)` I tried to pass in int64, but even that doesn't work. @DmytroBogatov is probably correct. – Prateek Bhuwania Jun 24 '19 at 06:35
  • @PrateekBhuwania try `time.Sleep(time.Duration(rand.Int63n(10))*time.Second)`. There is no automatic type casting in Go. As for my answer it is still correct: https://golang.org/pkg/time/#Duration – abhink Jun 24 '19 at 11:43
  • @abhink Yes, your solution is correct. I was just wondering if `time.Second` is an `int64` and `rand.Int63n()` also returns an `int64`, then why is there a type mismatch during multiplication ? – Prateek Bhuwania Jun 24 '19 at 19:31
7

If you try to run same rand.Intn several times, you will see always the same number in output

Just like its written in the official docu https://golang.org/pkg/math/rand/

Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run.

It rather should look like

rand.Seed(time.Now().UnixNano())
r := rand.Intn(100)
time.Sleep(time.Duration(r) * time.Millisecond)
mati kepa
  • 2,543
  • 19
  • 24