-
Notifications
You must be signed in to change notification settings - Fork 0
/
delay_context.go
56 lines (47 loc) · 990 Bytes
/
delay_context.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
package ps121
import (
"context"
"sync"
"time"
)
func ContextWithDelay(ctx context.Context, delay time.Duration) context.Context {
return &_DelayContext{
Context: ctx,
Delay: delay,
}
}
type _DelayContext struct {
Context context.Context
Delay time.Duration
done chan struct{}
onceInitDone sync.Once
}
func (self *_DelayContext) Deadline() (deadline time.Time, ok bool) {
deadline, hasDeadline := self.Context.Deadline()
if !hasDeadline {
return time.Time{}, false
}
return deadline.Add(self.Delay), false
}
func (self *_DelayContext) Done() <-chan struct{} {
self.onceInitDone.Do(func() {
self.done = make(chan struct{})
go func() {
<-self.Context.Done()
time.Sleep(self.Delay)
close(self.done)
}()
})
return self.done
}
func (self *_DelayContext) Err() error {
select {
case <-self.Done():
return self.Context.Err()
default:
return nil
}
}
func (self *_DelayContext) Value(key any) any {
return self.Context.Value(key)
}