Golang time.Sleep()用法及示例講解
在Go語言中,時間包提供了確定和查看時間的函數(shù)。 Go語言中的Sleep()函數(shù)用于在至少規(guī)定的持續(xù)時間d內(nèi)停止最新的go-routine。睡眠時間為負數(shù)或零將導致此方法立即返回。此外,此函數(shù)在時間包下定義。在這里,您需要導入“time”包才能使用這些函數(shù)。
用法:
func Sleep(d Duration)
此處,d是睡眠時間,以秒為單位。
返回值:它將在規(guī)定的時間內(nèi)暫停最新的go-routine,然后在睡眠結(jié)束后返回任何操作的輸出。
范例1:
// Golang program to illustrate the usage of
// Sleep() function
??
// Including main package
package main
??
// Importing fmt and time
import (
????"fmt"
????"time"
)
??
// Main function
func main() {
??
????// Calling Sleep method
????time.Sleep(8 * time.Second)
??
????// Printed after sleep is over
????fmt.Println("Sleep Over.....")
}輸出:
Sleep Over.....
在這里,在運行上述代碼后,當調(diào)用main函數(shù)時,由于使用了Sleep方法,因此在給定的時間內(nèi)停止了所述操作,然后打印了結(jié)果。
范例2:
// Golang program to illustrate the usage of
// Sleep() function
??
// Including main package
package main
??
// Importing time and fmt
import (
????"fmt"
????"time"
)
??
// Main function
func main() {
??
????// Creating channel using
????// make keyword
????mychan1:= make(chan string, 2)
??
????// Calling Sleep function of go
????go func() {
????????time.Sleep(2 * time.Second)
??
????????// Displayed after sleep overs
????????mychan1 <- "output1"
????}()
??
????// Select statement
????select {
??
????// Case statement
????case out:= <-mychan1:
????????fmt.Println(out)
??
????// Calling After method
????case <-time.After(3 * time.Second):
????????fmt.Println("timeout....1")
????}
??
????// Again Creating channel using
????// make keyword
????mychan2:= make(chan string, 2)
??
????// Calling Sleep method of go
????go func() {
????????time.Sleep(6 * time.Second)
??
????????// Printed after sleep overs
????????mychan2 <- "output2"
????}()
??
????// Select statement
????select {
??
????// Case statement
????case out:= <-mychan2:
????????fmt.Println(out)
??
????// Calling After method
????case <-time.After(3 * time.Second):
????????fmt.Println("timeout....2")
????}
}輸出:
output1
timeout....2
此處,在上面的代碼“output1”中,由于超時的持續(xù)時間(在After()方法中)大于睡眠時間(在Sleep()方法中)而被打印,因此,在顯示超時之前打印輸出,但是在此之后,以下情況發(fā)生了超時持續(xù)時間小于睡眠時間,因此在打印輸出之前顯示超時,因此將打印“timeout….2”。
到此這篇關(guān)于Golang time.Sleep()用法及代碼示例的文章就介紹到這了,更多相關(guān)Golang time.Sleep()用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決golang結(jié)構(gòu)體tag編譯錯誤的問題
這篇文章主要介紹了解決golang結(jié)構(gòu)體tag編譯錯誤的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05
一文帶你玩轉(zhuǎn)Golang Prometheus Eexporter開發(fā)
本文分兩大塊,一是搞清楚prometheus四種類型的指標Counter,Gauge,Histogram,Summary用golang語言如何構(gòu)造這4種類型對應(yīng)的指標,二是搞清楚修改指標值的場景和方式,感興趣的可以了解一下2023-02-02
Golang?Redis連接池實現(xiàn)原理及示例探究
這篇文章主要為大家介紹了Golang?Redis連接池實現(xiàn)示例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
Go語言并發(fā)編程之互斥鎖Mutex和讀寫鎖RWMutex
Go 語言中提供了很多同步工具,本文將介紹互斥鎖Mutex和讀寫鎖RWMutex的使用方法,想要具體了解的小伙伴,請參考下面文章詳細內(nèi)容,希望對你有所幫助2021-10-10

