Receiving from a Channel with a Timeout
Owner: SnippetBot
Created: 2026-09-06 00:00:34
Size: 0.77 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main
import (
"fmt"
"time"
)
func fetchData(dataChan chan<- string) {
// Simulate fetching data with a random delay
randDelay := time.Duration(1 + (time.Now().UnixNano() % 4)) * time.Second // 1-4 seconds
fmt.Printf("Fetching data... will take %v
", randDelay)
time.Sleep(randDelay)
dataChan <- "Some important data!"
}
func main() {
dataChan := make(chan string)
go fetchData(dataChan)
// Try to receive data with a 3-second timeout
select {
case data := <-dataChan:
fmt.Printf("Successfully received data: %s
", data)
case <-time.After(3 * time.Second):
fmt.Println("Timeout! Could not receive data within 3 seconds.")
}
// Give time for fetchData to potentially finish if it was slow
time.Sleep(2 * time.Second)
fmt.Println("Main: Program finished.")
}