在 Go 语言中,时间包提供了确定和查看时间的功能。 Go 语言中的AfterFunc()函数用于等待持续时间过去,然后在自己的 go-routine 中调用定义的函数“f”。而且,这个函数是在时间包下定义的。在这里,您需要导入“time”包才能使用这些功能。
句法:
func AfterFunc(d Duration, f func()) *Timer
这里,*Timer 是指向 Timer 的指针。
返回值:它返回一个Timer ,然后在其 Stop() 方法的帮助下用于取消调用。
示例 1:
// Golang program to illustrate the usage of
// AfterFunc() function
// Including main package
package main
// Importing fmt and time
import (
"fmt"
"time"
)
// Main function
func main() {
// Defining duration parameter of
// AfterFunc() method
DurationOfTime := time.Duration(3) * time.Second
// Defining function parameter of
// AfterFunc() method
f := func() {
// Printed when its called by the
// AfterFunc() method in the time
// stated above
fmt.Println("Function called by "+
"AfterFunc() after 3 seconds")
}
// Calling AfterFunc() method with its
// parameter
Timer1 := time.AfterFunc(DurationOfTime, f)
// Calling stop method
// w.r.to Timer1
defer Timer1.Stop()
// Calling sleep method
time.Sleep(10 * time.Second)
}
输出:
Function called by AfterFunc() after 3 seconds
这里,输出在 3 秒后返回,然后返回的计时器使用 Stop() 方法取消对函数的调用。然后程序在睡眠持续时间结束后退出。
示例 2:
// Golang program to illustrate the usage of
// AfterFunc() function
// Including main package
package main
// Importing fmt and time
import (
"fmt"
"time"
)
// Main function
func main() {
// Creating channel using
// make keyword
mychan := make(chan int)
// Calling AfterFunc() method
// with its parameters
time.AfterFunc(6*time.Second, func() {
// Printed after stated duration
// by AfterFunc() method is over
fmt.Println("6 seconds over....")
// loop stops at this point
mychan <- 30
})
// Calling for loop
for {
// Select statement
select {
// Case statement
case n := <-mychan:
// Printed after the loop stops
fmt.Println(n, "is arriving")
fmt.Println("Done!")
return
// Returned by default
default:
// Printed until the loop stops
fmt.Println("time to wait")
// Sleeps for 3 seconds
time.Sleep(3 * time.Second)
}
}
}
输出:
time to wait
time to wait
6 seconds over....
30 is arriving
Done!
在上面的例子中,在规定的持续时间结束后,通道返回其输出并且程序退出。