Skip to content
Related Articles

Related Articles

time.Sleep() Function in Golang With Examples
  • Last Updated : 01 Apr, 2020

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 in seconds 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:






// Golang program to illustrate the usage of
// Sleep() function
  
// Including main package
package main
  
// Importing fmt and time
import (
    "fmt"
    "time"
)
  
// Main function
func main() {
  
    // Calling Sleep method
    time.Sleep(8 * time.Second)
  
    // Printed after sleep is over
    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:




// Golang program to illustrate the usage of
// Sleep() function
  
// Including main package
package main
  
// Importing time and fmt
import (
    "fmt"
    "time"
)
  
// Main function
func main() {
  
    // Creating channel using
    // make keyword
    mychan1 := make(chan string, 2)
  
    // Calling Sleep function of go
    go func() {
        time.Sleep(2 * time.Second)
  
        // Displayed after sleep overs
        mychan1 <- "output1"
    }()
  
    // Select statement
    select {
  
    // Case statement
    case out := <-mychan1:
        fmt.Println(out)
  
    // Calling After method
    case <-time.After(3 * time.Second):
        fmt.Println("timeout....1")
    }
  
    // Again Creating channel using
    // make keyword
    mychan2 := make(chan string, 2)
  
    // Calling Sleep method of go
    go func() {
        time.Sleep(6 * time.Second)
  
        // Printed after sleep overs
        mychan2 <- "output2"
    }()
  
    // Select statement
    select {
  
    // Case statement
    case out := <-mychan2:
        fmt.Println(out)
  
    // Calling After method
    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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :