go / intermediate
Snippet
Managing Cancellation with context.WithTimeout
The context package is essential for managing the lifecycle and cancellation of concurrent processes. WithTimeout creates a derived context that automatically cancels itself after a specified duration, preventing goroutines from running indefinitely.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
func fetchData(ctx context.Context) {ctx, cancel := context.WithTimeout(ctx, 2*time.Second)defer cancel()select {case <-time.After(3 * time.Second):fmt.Println("Finished task")case <-ctx.Done():fmt.Println("Cancelled:", ctx.Err())}}
Breakdown
1
context.WithTimeout(ctx, 2*time.Second)
Creates a context that expires after 2 seconds.
2
defer cancel()
Ensures resources are released as soon as the function returns.
3
case <-ctx.Done():
Receives a signal when the timeout is reached or cancel is called.