In Go language, time packages supplies functionality for determining as well as viewing time.
The Sleep() function in Go language is used to stop the latest go-routine for at least the stated duration d. And a negative or zero duration of sleep will cause this method to return instantly. Moreover, this function is defined under the time package. Here, you need to import the “time” package to use these functions.
Syntax:
func Sleep(d Duration)
Here, d is the duration of time to sleep.
Return Value: It pauses the latest go-routine for the stated duration then returns the output of any operation after the sleep is over.
Example 1:
package main
import (
"fmt"
"time"
)
func main() {
time .Sleep(8 * time .Second)
fmt.Println( "Sleep Over....." )
}
|
Output:
Sleep Over.....
Here, after running the above code when the main function is called then due to Sleep method the stated operation is stopped for the given duration then the result is printed.
Example 2:
package main
import (
"fmt"
"time"
)
func main() {
mychan1 := make(chan string, 2)
go func() {
time .Sleep(2 * time .Second)
mychan1 <- "output1"
}()
select {
case out := <-mychan1:
fmt.Println(out)
case <- time .After(3 * time .Second):
fmt.Println( "timeout....1" )
}
mychan2 := make(chan string, 2)
go func() {
time .Sleep(6 * time .Second)
mychan2 <- "output2"
}()
select {
case out := <-mychan2:
fmt.Println(out)
case <- time .After(3 * time .Second):
fmt.Println( "timeout....2" )
}
}
|
Output:
output1
timeout....2
Here, in the above code “output1” is printed as the duration of timeout(in After() method) is greater than the sleep time(in Sleep() method) so, the output is printed before the timeout is displayed but after that, the below case has timeout duration less than the sleep time so, before printing the output the timeout is displayed hence, “timeout….2” is printed.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
20 Jun, 2023
Like Article
Save Article