广告
返回顶部
首页 > 资讯 > 后端开发 > GO >Golangtime.Sleep()用法及示例讲解
  • 342
分享到

Golangtime.Sleep()用法及示例讲解

gotime.Sleep()用法gotime.Sleep()gotime.Sleep 2023-02-28 11:02:08 342人浏览 八月长安
摘要

在Go语言中,时间包提供了确定和查看时间的函数。 Go语言中的Sleep()函数用于在至少规定的持续时间d内停止最新的go-routine。睡眠时间为负数或零将导致此方法立即返回。此

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….2”。

到此这篇关于Golang time.Sleep()用法及代码示例的文章就介绍到这了,更多相关Golang time.Sleep()用法内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

您可能感兴趣的文档:

--结束END--

本文标题: Golangtime.Sleep()用法及示例讲解

本文链接: https://www.lsjlt.com/news/197753.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作