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
+5k Java : Human readable password generator
+7.1k Golang : How To Use Panic and Recover
+2.8k Java : Random alphabets, alpha-numeric or numbers only string generator
+7.1k Golang : Variadic function arguments sanity check example
+10.7k Golang : Pagination with go-paginator configuration example
+9.3k Golang : Generate random integer or float number
+5.6k Golang : How to setup a disk space used monitoring service with Telegram bot
+4.5k Unix/Linux : How to find out the hard disk size?
+8k Golang : How to check if a string with spaces in between is numeric?
+11.2k Golang : Extract part of string with regular expression
+6.4k Golang : Handling Yes No Quit query input