How can we pause a thread in a Go program for a few milliseconds? We can use the Sleep func
, and this function is found in the time module.
By passing a Duration to Sleep, we can specify how long we want to wait. We can create a Duration with the type specifically, or just use an int64
value.
Here we use Sleep, which receives a Duration. We the pauses execution on the current goroutine for that duration of time. We call sleep 4 times for 100 ms each time.
time.Millisecond
, we get the correct multiplicand to convert seconds to nanoseconds.package main import ( "fmt" "time" ) func main() { for i := 0; i < 4; i++ { // Duration receives nanoseconds. d := time.Duration(100 * time.Millisecond) // Sleep for 100 ms. time.Sleep(d) fmt.Println(time.Now()) } }2025-02-08 07:45:34.612284 -0800 PST m=+0.101130376 2025-02-08 07:45:34.715586 -0800 PST m=+0.204435167 2025-02-08 07:45:34.816708 -0800 PST m=+0.305560792 2025-02-08 07:45:34.917828 -0800 PST m=+0.406684126
Suppose we want to sleep 1 second—how can we do this? We can multiply the count of seconds by the time.Second
constant.
time.Seconds
provide the number of nanoseconds in the specific unit of time.package main import ( "fmt" "time" ) func main() { fmt.Println(time.Now()) // Wait an entire second. // Do not bother specifying the duration, just use an int64 value. time.Sleep(1 * time.Second) fmt.Println(time.Now()) }2025-02-08 07:48:02.826416 -0800 PST m=+0.000030709 2025-02-08 07:48:03.827596 -0800 PST m=+1.001243584
Sleep is useful in many Go programs, although perhaps the most common use is for testing and debugging threaded programs. It is easier to call Sleep than do lots of computational work.