Sleeping in Golang

Sleeping in Go and how to pause execution and sleep for a number of seconds in Go (golang). We can use the time package from the standard library to sleep for a duration of time. You can use any duration of time, providing you use the constants provided.

In our example below we sleep for two seconds, and to illustrate the point, we print out the time before and after we do this.

This will only sleep the current goroutine, other parts will continue.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Copy to Clipboard
package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Printf("Current Unix Time: %v\n", time.Now().Unix())

	time.Sleep(2 * time.Second)

	fmt.Printf("Current Unix Time: %v\n", time.Now().Unix())
}

Other examples:

1
Copy to Clipboard
time.Sleep(500 * time.Millisecond)
1
2
Copy to Clipboard
inSeconds := 5
time.Sleep(time.Duration(inSeconds) * time.Second)

Example In Action

golang sleep for time