Search code examples
gorandomtimesleep

How to implement Random sleep in golang


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)

Solution

  • 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