You can create a timeout with the select statement. To use timeouts with concurrent goroutines, you must import "time".

Then, create a channel with time.After() which as parameter takes time. The call time.After(time.Second) would fill the channel after a second.

Example

Timeout

Combined with select, a simple timeout program can be created:


package main

import "fmt"
import "time"

func main() {
    select {
        case <- time.After(2 * time.Second):
            fmt.Println("Timeout!")
    }
}

This will print “Timeout!” after the time has passed.

Goroutine

Timeouts can be combined with goroutine calls. Call a goroutine f1 with a channel c1. Making go f1(c1). The goroutine writes in to the channel c <- "message" after waiting 10 seconds.

Then a timeout is made with time.After(). As this:


package main

import "fmt"
import "time"

func f1(c chan string) {
    for {
        time.Sleep(10 * time.Second)
        c <- "10 seconds passed"
    }
}

func main() {
   c1 := make(chan string)
   go f1(c1)

   select {
       case msg1 := <- c1:
           fmt.Println(msg1)
       case <- time.After(3 * time.Second):
           fmt.Println("Timeout!")
   }
}

See what happens.