温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Golang time.Sleep()怎么使用

发布时间:2023-02-28 10:56:44 来源:亿速云 阅读:106 作者:iii 栏目:开发技术

这篇文章主要讲解了“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()怎么使用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI