Golang Sleep Random Time

If you ever wondered how to sleep a random number of seconds with Go there is a simple way to do that. You can combine the math/rand package with the time package

package main

import (
  "fmt"
  "time"
  "math/rand"
)
  
func main() {
    rand.Seed(time.Now().UnixNano())
    n := rand.Intn(10) // n will be between 0 and 10
    fmt.Printf("Sleeping %d seconds...\n", n)
    time.Sleep(time.Duration(n)*time.Second)
    fmt.Println("Done")
}

Here is the expected output

Sleeping 4 seconds...
Done

As explained already in this article in order to use the rand.Intn function you first need to initialise the source with rand.Seed. Which in this case is being initialised with the current time expressed in microseconds

In the example above in order to sleep the process for a number of seconds we use time.Sleep. An handy function that comes directly from the Go standard library. We can then specify a duration that can be expressed in different unit of time

const (
    Nanosecond  Duration = 1
    Microsecond          = 1000 * Nanosecond
    Millisecond          = 1000 * Microsecond
    Second               = 1000 * Millisecond
    Minute               = 60 * Second
    Hour                 = 60 * Minute
)
Join the Golang Developers Community on Golang Cafe