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


Golang time.After()用法及代码示例


在Go语言中,时间包提供了确定和查看时间的函数。 Go语言中的After()函数用于等待经过的时间,然后在返回的通道上传递实际时间。此外,此函数在时间包下定义。在这里,您需要导入“time”软件包才能使用这些函数。

用法:

func After(d Duration) <-chan Time

此处,d是超时之前的持续时间,而chan是发送当前时间的通道。

返回值:它首先等待指定的时间,然后显示超时。

范例1:



// Golang program to illustrate the usage of 
// After() function in Golang 
  
// Including main package 
package main 
  
// Importing fmt and time 
import ( 
    "fmt"
    "time"
) 
  
// Creating a channel 
// Using var keyword 
var ch chan int
  
// Main function 
func main() { 
  
    // For loop 
    for i:= 1; i < 6; i++ { 
  
        // Prints these util loop stops 
        fmt.Println("****Welcome to GeeksforGeeks***") 
        fmt.Println("A CS-Portal!") 
    } 
  
    // Select statement 
    select { 
  
    // Using case statement to receive 
    // or send operation on channel and 
    // calling After() method with its 
    // parameter 
    case <-time.After(3 * time.Second):
  
        // Printed when timed out 
        fmt.Println("Time Out!") 
    } 
}

输出:

****Welcome to GeeksforGeeks***
A CS-Portal!
****Welcome to GeeksforGeeks***
A CS-Portal!
****Welcome to GeeksforGeeks***
A CS-Portal!
****Welcome to GeeksforGeeks***
A CS-Portal!
****Welcome to GeeksforGeeks***
A CS-Portal!
Time Out!    // Displayed after 3 seconds as mentioned in the above code

在上面的示例中,我们在select语句下使用了“case”语句,以便在通道上发送操作。此外,在for循环执行3秒后,此处将显示超时。

范例2:

// Golang program to illustrate the usage of 
// After() function in Golang 
  
// Including main package 
package main 
  
// Importing fmt and time 
import ( 
    "fmt"
    "time"
) 
  
// Main function 
func main() { 
  
    // Creating a channel 
    // Using make keyword 
    channel:= make(chan string, 2) 
  
    // Select statement 
    select { 
  
    // Using case statement to receive 
    // or send operation on channel 
    case output:= <-channel:
        fmt.Println(output) 
  
    // Calling After() method with its 
    // parameter 
    case <-time.After(5 * time.Second):
  
        // Printed after 5 seconds 
        fmt.Println("Its timeout..") 
    } 
}

输出:

Its timeout..

在这里,我们使用了“make”关键字来创建频道,然后像上面的示例一样,在select语句下也使用case语句,但是在这里使用了两次。第一个用于返回输出,第二个用于调用通道上的After()方法。此后,将在指定的时间显示超时。




相关用法


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