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
+21.9k Golang : Change file read or write permission example
+7.3k Golang : Qt get screen resolution and display on center example
+24.4k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+13.1k Golang : Get query string value on a POST request
+14.3k Golang : Put UTF8 text on OpenCV video capture image frame
+21.4k Golang : Create PDF file from HTML file
+7.7k Golang : Test a slice of integers for odd and even numbers
+4.3k Fix fatal error: evacuation not done in time problem
+6.8k Golang : Find network service name from given port and protocol
+20.5k Golang : Convert long hexadecimal with strconv.ParseUint example
+3.9k Golang : Reclaim memory occupied by make() example
+3.3k Golang : Check if a word is countable or not