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
+16.2k Golang : Linked list example
+20.8k Golang : Securing password with salt
+20.7k Golang : How to run Golang application such as web server in the background or as daemon?
+12.4k Golang : Convert spaces to tabs and back to spaces example
+9.9k Golang : Calculate Relative Strength Index(RSI) example
+29k Golang : Calculate percentage change of two values
+4.7k Linux/Unix/PHP : Restart PHP-FPM
+18.3k Golang : Compare floating-point numbers
+4.9k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+5.1k Javascript : Get operating system and browser information
+20.5k Golang : Join arrays or slices example
+4.4k Golang : Return multiple values from function