forked from hoanhan101/ultimate-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context_3.go
47 lines (37 loc) · 936 Bytes
/
context_3.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
46
47
// ------------
// WithDeadline
// ------------
package main
import (
"context"
"fmt"
"time"
)
type data struct {
UserID string
}
func main() {
// Set a deadline.
deadline := time.Now().Add(150 * time.Millisecond)
// Create a context that is both manually cancellable and will signal
// a cancel at the specified date/time.
// We use Background as our parents context and set out deadline time.
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
// Create a channel to received a signal that work is done.
ch := make(chan data, 1)
// Ask a Goroutine to do some work for us.
go func() {
// Simulate work.
time.Sleep(200 * 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")
}
}