How to make a delay in Go Language

The Sleep() method pauses the execution of the current thread temporarily. Sleep() is part of the time package. This method takes the duration as an argument. 


Here is an example code that shows how to make a delay in Go Language.

Here, 3*time.Second, means 3 seconds. This will sleep the current goroutine so other goroutines will continue to run.
package main

import (
"fmt"
"time"
)

func main() {
// Before sleep
fmt.Println("Before sleep the time is:", time.Now().Unix())

// pauses execution for 3 seconds
time.Sleep(3 * time.Second)

// After sleep
fmt.Println("After sleep the time is:", time.Now().Unix())
}

Output:




Goroutines

Goroutines are methods that run concurrently with other methods. Goroutines can be thought of as lightweight threads. The cost of creating a Goroutine is tiny when compared to a thread. 
Every concurrently executing activity in the Go language is known as Goroutines.


Another Example: Go program to print Odd, Even & Natural Numbers using Goroutines

The odd Goroutine sleeps initially for 300 milliseconds and then prints 1, then sleeps again and prints 2 and the same cycle happens till it prints 9. Similarly, the even Goroutine prints even numbers from 1 to 9 and has 450 milliseconds of sleep time. Similarly, the Natural Goroutine prints natural numbers from 1 to 9 has 350 milliseconds. The main Goroutine initiates the Odd, Even, and Natural Goroutines sleeps for 3000 milliseconds and then terminates.
package main

import (
"fmt"
"time"
)

func Natural() {
for i := 1; i <= 9; i++ {
time.Sleep(350 * time.Millisecond)
fmt.Printf("%d ", i)

}
}

func Odd() {
for i := 1; i <= 9; i++ {
time.Sleep(300 * time.Millisecond)
/* If 'i' is odd then print it */
if i%2 != 0 {
fmt.Printf("%d ", i)
}
}
}

func Even() {
for i := 1; i <= 9; i++ {
time.Sleep(450 * time.Millisecond)
/* If 'i' is even then print it */
if i%2 == 0 {
fmt.Printf("%d ", i)
}
}
}
func main() {
go Odd()
go Even()
go Natural()
time.Sleep(4000 * time.Millisecond)
fmt.Println("main terminated")
}

Output:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete