日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Golang?time.Sleep()用法及示例講解_Golang

作者:純凈天空 ? 更新時間: 2023-07-02 編程語言

在Go語言中,時間包提供了確定和查看時間的函數(shù)。 Go語言中的Sleep()函數(shù)用于在至少規(guī)定的持續(xù)時間d內(nèi)停止最新的go-routine。睡眠時間為負(fù)數(shù)或零將導(dǎo)致此方法立即返回。此外,此函數(shù)在時間包下定義。在這里,您需要導(dǎo)入“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.....

在這里,在運行上述代碼后,當(dāng)調(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”。

原文鏈接:https://vimsky.com/examples/usage/time-sleep-function-in-golang-with-examples.html

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新