Golang time.Sleep()函数及示例

Golang time.Sleep()函数及示例

在Go语言中,time包提供了确定和查看时间的功能。

Golang中的 Sleep() 函数用于至少在指定时间d内停止最新的go-routine。负值或零持续时间的睡眠将导致该方法立即返回。此外,该函数在time包中定义。在这里,您需要导入“time”包以使用这些功能。

语法:

func Sleep(d Duration)
Go

在这里,d是以秒为单位的时间持续时间。

返回值:它暂停最新的go-routine的指定持续时间,然后返回睡眠后任何操作的输出。

示例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.....")
} 
Go

输出:

Sleep Over.....
Go

在上面的代码运行后,当调用主函数时,由于Sleep方法停止了给定时间的操作,然后打印了结果。

示例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")
    }
} 
Go

输出:

output1
timeout....2
Go

在上面的代码中,“output1”被打印为超时时间(在After()方法中)大于睡眠时间(在Sleep()方法中),所以输出在超时显示之前已打印,但之后,下面的案例超时持续时间小于睡眠时间,因此在打印输出之前显示超时,因此打印了“timeout….2”。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册