In this article, we will see how to implement the random sleep in Golang using the time
and math/rand
packages.
The time
package in Golang has a function called the time.Sleep
to pause the execution of a program for a specified duration. The time.Sleep
function takes time.Duration
as an argument. time.Duration tells how much time the execution of program has to be paused.
All we have to do is generating this time.Duration value randomly.
To generate the random durations in your program, you can use the math/rand
package. The math/rand
package provides various functions to generate random numbers, such as rand.Intn
and rand.Float64
.
Following is the example of how to generate a random sleep duration between 1 and 5 seconds:
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
fmt.Println("Starting...")
rand.Seed(time.Now().UnixNano())
minSleep := 1
maxSleep := 5
randomSleep := rand.Intn(maxSleep-minSleep+1) + minSleep
sleepDuration := time.Duration(randomSleep) * time.Second
fmt.Printf("Sleeping for %d seconds\n", randomSleep)
time.Sleep(sleepDuration)
fmt.Println("Finished.")
}
Explanation:
In the above example, we first seed the random number generator with the current time using rand.Seed(time.Now().UnixNano())
. This ensures that the random number generator produces different sequences of numbers each time the program runs. We then use rand.Intn
to generate a random sleep duration between 1 and 5 seconds. We then convert the random sleep duration to a time.Duration
value and use the time.Sleep
function to pause the execution of the program for the random sleep duration.