Golang Sleep Random Time Example

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

Here is the expected output

Sleeping 4 seconds...

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