Golang time.Sleep()怎么使用

这篇文章主要讲解了“Golang time.Sleep()怎么使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Golang time.Sleep()怎么使用”吧!

在Go语言中,时间包提供了确定和查看时间的函数。 Go语言中的Sleep()函数用于在至少规定的持续时间d内停止最新的go-routine。睡眠时间为负数或零将导致此方法立即返回。此外,此函数在时间包下定义。在这里,您需要导入“time”包才能使用这些函数。

用法:

func Sleep(d Duration)

此处,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.....") 
}

输出:

Sleep Over.....

在这里,在运行上述代码后,当调用main函数时,由于使用了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") 
    } 
}

输出:

output1
timeout....2

此处,在上面的代码“output1”中,由于超时的持续时间(在After()方法中)大于睡眠时间(在Sleep()方法中)而被打印,因此,在显示超时之前打印输出,但是在此之后,以下情况发生了超时持续时间小于睡眠时间,因此在打印输出之前显示超时,因此将打印“timeout&hellip;.2”。

感谢各位的阅读,以上就是“Golang time.Sleep()怎么使用”的内容了,经过本文的学习后,相信大家对Golang time.Sleep()怎么使用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程之家,小编将为大家推送更多相关知识点的文章,欢迎关注!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐