Golang Sleep

As developers, we encounter scenarios where we need a program to pause or wait for a specific duration. For example, you could pause a specific thread and allow other threads to execute.

This guide will help you learn how to use the sleep function in the go programming language.

Money-Back Guarantee if otherwise 😊.

Golang Sleep Function

The time package provides the sleep function in Go. Hence, you will need to import it before use.

The clause below imports the time package:

import "time"

Once imported, you can use the sleep function. We can express the function syntax as:

func Sleep(d Duration)

The sleep() method takes the duration as the argument. To specify the specific time, we follow the syntax as:

value * time.unit

For example, to tell the sleep function to sleep for 10 seconds, we do:

time.Sleep(10 * time.Second)

This will tell the program to pause for 10 seconds.

The example below illustrates how to use the Sleep() method.

package main
import (
func main() {
        fmt.Println("Before Sleep => ", time.Now().Format("2006-01-02 15:04:05"))
        time.Sleep(10 * time.Second)
        fmt.Println("After Sleep => ", time.Now().Format("2006-01-02 15:04:05"))

In the example ab0ve, we capture the time before executing the sleep function. We then sleep for 10 seconds and capture the time after it.

An example output is as shown:

$ go run sleep.go
Before Sleep =2022-01-22 11:29:36
After Sleep =2022-01-22 11:29:46

Notice the elapsed time is precisely 10 seconds.

You can also specify other units of time in the sleep method. The example below tells the program to sleep for 1 minute.

time.Sleep(1 * time.Minute)

An example output:

Before Sleep =2022-01-22 11:31:23
After Sleep =2022-01-22 11:32:23

The program sleeps for exactly 60 seconds (or 1 minute).


This guide helps you understand how to use the sleep() method in the Go programming language. This can come in handy when working with concurrent programming.

Happy coding!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list