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.
Example. 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.
Info We construct the Duration from nanoseconds. With 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
Duration. Suppose we want to sleep 1 second—how can we do this? We can multiply the count of seconds by the time.Second constant.
Info Sleep receives nanoseconds, but the constants in time like 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.