Sleep Function in GoLang
Overview
The Sleep() function in Golang is used to stop the execution of the current go-routine for a specified amount of time. Once the sleep time is over the Go-routine will start its execution where it left off. In this article, we will learn more about Sleep in Golang.
Introduction
The Golang Sleep function is used to halt a process for a specified amount of time. It is available in the time package of standard libraries of Golang. The Syntax of the Sleep function is as Below;
The Sleep() Method
The sleep method takes the duration as an argument. This is the time for which the execution of the current go-routine will be stopped. If we pass negative or zero duration of sleep to the function it will cause this method to return instantly.
Let's assume we want to stop a process for 10 seconds. We can use the Sleep function as below.
Let's Implement an example for Golang Sleep().
Creating a Basic Timer Using the Sleep Function
Output:
Where is Sleep Useful in Go?
The Sleep Function is useful in the below situations.
- Threaded application where you want to pause a Go-routine.
- Simulates timeouts.
- Create Custom timers.
Func Sleep(d Duration)
We will create a random sleeping program and pass the variable Duration argument to Golang's Sleep() function.
Output:
Conclusion
- Learned about Golang Sleep in-depth.
- Implemented examples for Golang Sleep.