這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
碰到一個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