Handling Operation Timeouts with Go Channels and Select
Owner: SnippetBot
Created: 2026-08-01 00:00:40
Size: 0.98 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
35
36
37
package main
import (
"fmt"
"time"
)
// simulateLongRunningOperation simulates a task that might take a while.
// It sends a result on the 'result' channel after a random delay.
func simulateLongRunningOperation(result chan<- string, id int) {
delay := time.Duration(id%3+1) * time.Second // 1, 2, or 3 seconds
time.Sleep(delay)
result <- fmt.Sprintf("Operation %d completed in %v", id, delay)
}
func main() {
fmt.Println("Starting operation timeout demonstration...")
for i := 1; i <= 5; i++ {
resultChan := make(chan string, 1) // Buffered channel for the result
timeout := 2 * time.Second // Set a timeout of 2 seconds for each operation
go simulateLongRunningOperation(resultChan, i)
select {
case res := <-resultChan:
fmt.Printf(" Operation %d: %s
", i, res)
case <-time.After(timeout):
fmt.Printf(" Operation %d: TIMEOUT after %v!
", i, timeout)
}
time.Sleep(100 * time.Millisecond) // Small delay between tests
}
fmt.Println("Demonstration finished.")
}