time.After() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The After() function in Go language is used to wait for the duration of time to pass and after that it delivers the actual time on the returned channel. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions.
Syntax:
func After(d Duration) <-chan Time
Here, d is the duration of time before time out, and chan is the channel where current time is sent.
Return Value: It first waits for the stated time and then displays timeout.
Example 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 w3wiki***" ) 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!" ) } } |
Output:
****Welcome to w3wiki*** A CS-Portal! ****Welcome to w3wiki*** A CS-Portal! ****Welcome to w3wiki*** A CS-Portal! ****Welcome to w3wiki*** A CS-Portal! ****Welcome to w3wiki*** A CS-Portal! Time Out! // Displayed after 3 seconds as mentioned in the above code
In the above example, we have used the “case” statement under the select statement in order to send operation on the channel. Moreover, here time out will be displayed after 3 seconds of the execution of for loop.
Example 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.." ) } } |
Output:
Its timeout..
Here, we have used the “make” keyword in order to create a channel then like the above example here also case statement is used under a select statement but here it’s used twice. The first one is used to return output and the second one is used to call After() method on the channel. After this, the timeout is displayed in the stated time.