Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Random sleep in golang

Tags:

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) 
like image 833
Ravichandra Avatar asked Jun 14 '17 05:06

Ravichandra


2 Answers

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

like image 71
abhink Avatar answered Nov 17 '22 16:11

abhink


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) 
like image 41
matson kepson Avatar answered Nov 17 '22 16:11

matson kepson