-
Notifications
You must be signed in to change notification settings - Fork 168
/
context_4.go
45 lines (36 loc) · 843 Bytes
/
context_4.go
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
38
39
40
41
42
43
44
45
// -----------
// WithTimeout
// -----------
package main
import (
"context"
"fmt"
"time"
)
type data struct {
UserID string
}
func main() {
// Set a duration.
duration := 150 * time.Millisecond
// Create a context that is both manually cancellable and will signal
// a cancel at the specified duration.
ctx, cancel := context.WithTimeout(context.Background(), duration)
defer cancel()
// Create a channel to received a signal that work is done.
ch := make(chan data, 1)
// Ask the goroutine to do some work for us.
go func() {
// Simulate work.
time.Sleep(50 * time.Millisecond)
// Report the work is done.
ch <- data{"123"}
}()
// Wait for the work to finish. If it takes too long move on.
select {
case d := <-ch:
fmt.Println("work complete", d)
case <-ctx.Done():
fmt.Println("work cancelled")
}
}