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
+6.1k Golang : Grab news article text and use NLP to get each paragraph's sentences
+8.9k Golang : Gaussian blur on image and camera video feed examples
+14.8k Golang : Get URI segments by number and assign as variable example
+9.7k Golang : Eroding and dilating image with OpenCV example
+13k Golang : Get terminal width and height example
+10.6k Golang : Select region of interest with mouse click and crop from image
+10.9k Golang : Natural string sorting example
+12.1k Golang : Find and draw contours with OpenCV example
+7.9k Golang : Ways to recover memory during run time.
+6.8k Golang : Experimental emojis or emoticons icons programming language
+11.7k Golang : Convert(cast) float to int
+16.8k Golang : Gzip file example