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
+7.7k Golang Hello World Example
+7.1k Golang : How to convert strange string to JSON with json.MarshalIndent
+15.2k Golang : rune literal not terminated error
+10.7k Golang : Fix go.exe is not compatible with the version of Windows you're running
+12.4k Golang : Remove or trim extra comma from CSV
+12.8k Golang : Handle or parse date string with Z suffix(RFC3339) example
+6.5k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+22.4k Golang : untar or extract tar ball archive example
+20.4k Golang : Convert date string to variants of time.Time type examples
+30.5k Golang : Interpolating or substituting variables in string examples
+8.9k Golang : Create and shuffle deck of cards example