Golang : Timeout example
It is important for programs to know when to abort when connecting to external resources. One such example is the net.DialTimeout()
function and if you looking to implement timeout feature in Golang, it is pretty easy with channels and select.
This code example below simulates a situation when a timeout occurred.
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan bool, 1)
go func() {
select {
case m := <-c:
// do something
handle(m)
case <-time.After(3 * time.Second):
fmt.Println("timed out")
}
}()
time.Sleep(5 * time.Second)
}
func handle(m bool) {}
References :
See also : Golang : Call a function after some delay(time.Sleep and Tick)
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.7k Golang : Simple file scaning and remove virus example
+11.4k Golang : How to flush a channel before the end of program?
+8k Javascript : Put image into Chrome browser's console
+6.1k Golang : Compound interest over time example
+7.4k Golang : File system scanning
+9k Golang : Inject/embed Javascript before sending out to browser example
+48.3k Golang : How to convert JSON string to map and slice
+6.1k Golang : Convert Chinese UTF8 characters to Pin Yin
+19.9k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+14.3k Golang : Chunk split or divide a string into smaller chunk example
+7.4k Golang : Not able to grep log.Println() output