我正在嘗試編寫一個程序,該程序會在十進制數的隨機時間間隔內暫停。這是不工作的程序:package mainimport ( "fmt" "math/rand" "time")var test intfunc main() { intervalGenerate()}func intervalGenerate() { var randint float64 rand.Seed(time.Now().UnixNano()) randInterval := randFloats(3, 7, 1) randint = randInterval[0] duration := time.Duration(randint) * time.Second fmt.Println("Sleeping for", duration) time.Sleep(duration) fmt.Println("Resuming")}func randFloats(min, max float64, n int) []float64 { res := make([]float64, n) for i := range res { res[i] = min + rand.Float64()*(max-min) } return res}目前生成的隨機數介于 3 和 7(包括小數)之間,但 Sleep 會四舍五入到最接近的整數。據我了解,這失敗的原因是因為Sleep需要Duration,這是一個Int64:func Sleep(d Duration)有沒有辦法讓程序休眠幾分之一秒?去游樂場: https: //play.golang.org/p/z-dnDBnUfxr
1 回答

狐的傳說
TA貢獻1804條經驗 獲得超3個贊
根據您需要的粒度級別使用 time.Millisecond、time.Microsecond 或 time.Nanosecond。
// sleep for 2.5 seconds
milliseconds := 2500
time.Sleep(time.Duration(milliseconds) * time.Millisecond)
- 1 回答
- 0 關注
- 180 瀏覽
添加回答
舉報
0/150
提交
取消