Timeout long-running operations
The previous recipe describes the concept of executing the code with some delay. The same concept can be used to implement the timeout for long running operations. This recipe will illustrate how this can be done.
How to do it...
- Open the console and create the folder
chapter04/recipe11
. - Navigate to the directory.
- Create the
timeout.go
file with the following content:
package main import ( "fmt" "time" ) func main() { to := time.After(3 * time.Second) list := make([]string, 0) done := make(chan bool, 1) fmt.Println("Starting to insert items") go func() { defer fmt.Println("Exiting goroutine") for { select { case <-to: fmt.Println("The time is up") done <- true return default: list = append(list, time.Now().String...