Sleeping in Golang

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
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())
}

golang sleep for time