As developers, we encounter scenarios where we need a program to pause or wait for a specific duration. For example, you could pause a specific thread and allow other threads to execute.
This guide will help you learn how to use the sleep function in the go programming language.
Money-Back Guarantee if otherwise 😊.
Golang Sleep Function
The time package provides the sleep function in Go. Hence, you will need to import it before use.
The clause below imports the time package:
Once imported, you can use the sleep function. We can express the function syntax as:
func Sleep(d Duration)
The sleep() method takes the duration as the argument. To specify the specific time, we follow the syntax as:
For example, to tell the sleep function to sleep for 10 seconds, we do:
This will tell the program to pause for 10 seconds.
The example below illustrates how to use the Sleep() method.
import (
"fmt"
"time"
)
func main() {
fmt.Println("Before Sleep => ", time.Now().Format("2006-01-02 15:04:05"))
time.Sleep(10 * time.Second)
fmt.Println("After Sleep => ", time.Now().Format("2006-01-02 15:04:05"))
}
In the example ab0ve, we capture the time before executing the sleep function. We then sleep for 10 seconds and capture the time after it.
An example output is as shown:
Before Sleep => 2022-01-22 11:29:36
After Sleep => 2022-01-22 11:29:46
Notice the elapsed time is precisely 10 seconds.
You can also specify other units of time in the sleep method. The example below tells the program to sleep for 1 minute.
An example output:
After Sleep => 2022-01-22 11:32:23
The program sleeps for exactly 60 seconds (or 1 minute).
Conclusion
This guide helps you understand how to use the sleep() method in the Go programming language. This can come in handy when working with concurrent programming.
Happy coding!