-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwith_deadline.go
62 lines (48 loc) · 1.34 KB
/
with_deadline.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package byo_context
import (
"errors"
"time"
)
var DeadlineExceeded = errors.New("context deadline exceeded")
type deadlineCtx struct {
cancelCtx // embed the cancelCtx to get the cancel() method
deadline time.Time
}
// func (c *deadlineCtx) Done() <-chan struct{} derived from cancelCtx
// func (c *deadlineCtx) Err() error derived from cancelCtx
func (c *deadlineCtx) Deadline() (time.Time, bool) {
return c.deadline, true
}
func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
if cur, ok := parent.Deadline(); ok && cur.Before(deadline) {
// parent has a deadline that is sooner than the deadline
// keep parent deadline
return WithCancel(parent)
}
c := &deadlineCtx{
cancelCtx: embedCancelCtx(parent),
}
parent.(treeOps).addChild(c)
c.deadline = deadline
dur := time.Until(deadline)
if dur <= 0 {
// the deadline has already passed
c.cancel(DeadlineExceeded)
return c, func() {}
}
time.AfterFunc(dur, func() {
c.cancel(DeadlineExceeded) // cancel the context after the deadline has passed
})
return c, func() {
c.cancel(Canceled)
}
}
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
return WithDeadline(parent, time.Now().Add(timeout))
}
func embedCancelCtx(parent Context) cancelCtx {
return cancelCtx{
Context: parent,
done: make(chan struct{}),
}
}