How to Use the time.Sleep() Function in Golang

Golang time.Sleep() function is used to stop the execution of the current go-routine for a specified amount of time.

Syntax

func Sleep(dur Duration)

Parameters

The dur is the duration of time in seconds to sleep.

Return value

The time.Sleep() function pauses the latest go-routine for the stated duration and returns the operation’s output after sleep.

Important note

The time.Sleep() function blocks the current Goroutine and will not allow any other Goroutines to run while it’s sleeping. This can induce a performance issue if the Goroutine is sleeping for a long time.

Example 1

Write a Golang program that will put the program to sleep for 5 seconds.

package main

import (
  "fmt"
  "time"
)

func main() {
  fmt.Println("Started")
  time.Sleep(5 * time.Second)
  fmt.Println("Finished")
}

Output

Started
// 5 seconds sleep
Finished

Example 2

Here’s another Go program that demonstrates the use of channels, goroutines, and the select statement for handling timeouts with different channels:

package main

import (
  "fmt"
  "time"
)

func main() {
  channel1 := make(chan string, 2)
  channel2 := make(chan string, 2)

  go func() {
    time.Sleep(2 * time.Second)
    channel1 <- "message from channel 1"
  }()

  go func() {
    time.Sleep(4 * time.Second)
    channel2 <- "message from channel 2"
  }()

 for i := 0; i < 2; i++ {
  select {
    case msg1 := <-channel1:
      fmt.Println("Received:", msg1)
    case msg2 := <-channel2:
      fmt.Println("Received:", msg2)
    case <-time.After(3 * time.Second):
      fmt.Println("Timeout occurred")
    }
  }
}

Output

Received: message from channel 1
Received: message from channel 2

    That’s it.

    Similar Posts

    Golang Time.Year()

    Golang Time.Hour()

    Golang Time.Day()

    Golang Time.Add()

    Golang Time.AddDate()

    Golang Time.After()

    Golang Time.Date()

    Golang Time.AppendFormat()

    Golang Time.Before()

    Golang Time.Clock()

    Leave a Comment