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
+17.7k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+8.6k Golang : Turn string or text file into slice example
+4.5k Clean up Visual Studio For Mac installation failed disk full problem
+5.2k Golang : Process non-XML/JSON formatted ASCII text file example
+26.5k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+27.7k Golang : Get first few and last few characters from string
+11.7k Golang : http.Get example
+4.6k Golang : What is StructTag and how to get StructTag's value?
+20.8k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+7.7k Golang : Gorilla web tool kit schema example
+17.2k Golang : Send email with attachment
+17.5k Golang : Get host name or domain name from IP address