在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()方法。此后,将在指定的时间显示超时。
相关用法
- Golang math.Lgamma()用法及代码示例
- Golang math.Float64bits()用法及代码示例
- Golang atomic.AddInt64()用法及代码示例
- Golang atomic.StoreInt64()用法及代码示例
- Golang reflect.FieldByIndex()用法及代码示例
- Golang string.Contains用法及代码示例
- Golang bits.Sub()用法及代码示例
- Golang io.PipeWriter.CloseWithError()用法及代码示例
- Golang time.Round()用法及代码示例
- Golang reflect.AppendSlice()用法及代码示例
- Golang reflect.ChanOf()用法及代码示例
- Golang flag.Bool()用法及代码示例
- Golang time.Sleep()用法及代码示例
- Golang time.Time.Year()用法及代码示例
- Golang reflect.DeepEqual()用法及代码示例
- Golang reflect.Indirect()用法及代码示例
- Golang reflect.CanAddr()用法及代码示例
- Golang reflect.CanInterface()用法及代码示例
- Golang reflect.CanSet()用法及代码示例
- Golang reflect.Cap()用法及代码示例
注:本文由纯净天空筛选整理自nidhi1352singh大神的英文原创作品 time.After() Function in Golang With Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。