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
+10.2k Golang : Find age or leap age from date of birth example
+3.8k MariaDB/MySQL : How to get version information
+4.8k Linux : Disable and enable IPv4 forwarding
+12.9k Golang : Chunk split or divide a string into smaller chunk example
+9.6k Golang : Bubble sort example
+6.5k Golang : Lock executable to a specific machine with unique hash of the machine
+9.2k Android Studio : Checkbox for user to select options example
+9k Golang : Use regular expression to get all upper case or lower case characters example
+12.5k Golang : How to get year, month and day?
+10.7k Golang : convert(cast) float to string
+23.5k Golang : Change file read or write permission example
+17k Golang : Iterating Elements Over A List