golang隨機time.sleep的Duration問題

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

碰到一個Golang time.Sleep()的問題,這golang的time.sleep的功能貌似要比python ruby都要精細些,python的等待只是time.sleep()而已,而golang可以time.Sleep(10 * time.Second) 毫秒、秒分時等不同日期來搞… 大事不幹,淨整些沒用的…  


該文章寫的有些亂,歡迎來噴 ! 另外文章後續不斷更新中,請到原文地址查看更新http://xiaorui.cc/?p=3034

重現一下問題,用math/rannd得到10以內的隨機數,然後time.sleep()等待…

Pythonnum := rand.Int31n(10)time.sleep(num * time.Second)
123  num := rand.Int31n(10)time.sleep(num * time.Second)

會遇到下面的問題:

Python#xiaorui.cc# command-line-arguments./lock.go:88: invalid operation: int(DefaultTimeout) * time.Second (mismatched types int and time.Duration)
1234  #xiaorui.cc# command-line-arguments./lock.go:88: invalid operation: int(DefaultTimeout) * time.Second (mismatched types int and time.Duration)


解決的方法:
    

Pythontime.Sleep(time.Duration(num) * time.Second)
12  time.Sleep(time.Duration(num) * time.Second)

期初原因以為是rand隨機數有問題,簡單看了rand的函數說明感覺沒問題! 下面是產生的原因:

Pythonfunc Sleep(d Duration) Sleep pauses the current goroutine for at least the duration d. A negative or zero duration causes Sleep to return immediately.
123  func Sleep(d Duration)    Sleep pauses the current goroutine for at least the duration d. A negative or zero duration causes Sleep to return immediately.

int32 and time.Duration are different types. You need to convert the int32 to a time.Duration, such as time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond).

下面是個完整的golang隨機數,然後time.sleep()的例子:

Pythonpackage mainimport ( "fmt" "math/rand" "time")func main() { rand.Seed(time.Now().UnixNano()) for i := 0; i < 10; i++ { x := rand.Intn(10) fmt.Println(x) time.Sleep(time.Duration(x) * time.Second) }}
1234567891011121314151617  package main import (    "fmt"    "math/rand"    "time") func main() {    rand.Seed(time.Now().UnixNano())    for i := 0; i < 10; i++ {        x := rand.Intn(10)        fmt.Println(x)        time.Sleep(time.Duration(x) * time.Second)    }}

Golang的time.sleep雖然可以直接用數字,但不能是float浮點型.

Pythontime.Sleep(1 * time.Second) //可以time.Sleep(1.1 * time.Second) //BUGtime.Sleep(time.Duration(yourTime) * time.Second) //可以
1234  time.Sleep(1 * time.Second)  //可以time.Sleep(1.1 * time.Second) //BUGtime.Sleep(time.Duration(yourTime) * time.Second) //可以

提示的錯誤是, constant 1.1 truncated to integer 。至於原因到這裡看 https://golang.org/pkg/time/#Duration

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.