-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
36 lines (30 loc) · 737 Bytes
/
context.go
File metadata and controls
36 lines (30 loc) · 737 Bytes
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
package main
import (
"context"
"fmt"
"time"
)
func slowOperation(ctx context.Context) {
for {
select {
case <-time.After(1 * time.Second):
// Simulate doing a piece of work
fmt.Println("Working...")
case <-ctx.Done():
// The context was cancelled or timed out
fmt.Println("Worker stopping:", ctx.Err())
return
}
}
}
func main() {
// 1. Create a context that expires after 2.5 seconds
ctx, cancel := context.WithTimeout(context.Background(), 2500*time.Millisecond)
// 2. Always defer cancel() to prevent context leaks
defer cancel()
// 3. Start the worker
go slowOperation(ctx)
// 4. Wait long enough to see the timeout happen
time.Sleep(4 * time.Second)
fmt.Println("Main program exiting.")
}