The sleep function is essential in cases where we want to stop the execution of the current thread temporarily. This is quite useful when we want to block current thread to let other threads do the work. In this post, we are going to explore Sleep() function in Golang.
Importing time package for Sleep() Function
To use the sleep function we need to import the time package. It has a built-in sleep function available that takes sleep duration as an argument.
import "time"
The Sleep() Method
The sleep method takes the duration as an argument. Now, specifying that is a bit tricky. We need to insert the amount and multiply with the defined primitive such as time.Second
.
time.Sleep(10 * time.Second) // sleep for 10 seconds
Here is an example code that shows how the sleep function works.
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Before sleep the time is:", time.Now().Unix()) // Before sleep the time is: 1257894000
time.Sleep(2 * time.Second) // pauses execution for 2 seconds
fmt.Println("After sleep the time is:", time.Now().Unix()) // After sleep the time is: 1257894002
}
Creating a basic timer using the sleep function
The sleep function can be used to do many things. Here we create a very basic timer that takes in the number of seconds and executes as a countdown timer.
package main
import (
"fmt"
"time"
)
func timer(s int) {
// run infinite loop
for {
// check if end condition is met
if s <= 0 {
break
} else {
fmt.Println(s)
time.Sleep(1 * time.Second) // wait 1 sec
s-- // reduce time
}
}
}
func main() {
timer(10) // run timer for 10 seconds
// output
// 10
// 9
// 8
// 7
// 6
// 5
// 4
// 3
// 2
// 1
}
Where is sleep useful in Go?
The sleep method pauses the execution of the current thread temporarily. This type of task is important in many cases. In concurrent programming in Go, the sleep method is often used to block a thread temporarily and let other threads execute. It can also be used to simulate timeouts and create custom timers. This utility method is really handy when we are creating a system software.