当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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




相关用法


注:本文由纯净天空筛选整理自nidhi1352singh大神的英文原创作品 time.Sleep() Function in Golang With Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。