-
Notifications
You must be signed in to change notification settings - Fork 0
/
event_loop.go
84 lines (64 loc) · 1.84 KB
/
event_loop.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package coro
import (
"context"
"sync"
"time"
chrono "github.com/nnikolash/go-chrono"
)
type EventLoop interface {
Clock() chrono.Clock
AddTask(task func(ctx Context)) chrono.Timer
AddDelayedTask(d time.Duration, task func(ctx Context)) chrono.Timer
AddPlannedTask(t time.Time, task func(ctx Context)) chrono.Timer
AddPlannedTaskCtx(ctx context.Context, t time.Time, task func(ctx Context))
}
var DefaultEventLoop = NewEventLoop(chrono.DefaultClock)
func AddTask(task func(ctx Context)) chrono.Timer {
return DefaultEventLoop.AddTask(task)
}
func AddDelayedTask(d time.Duration, task func(ctx Context)) chrono.Timer {
return DefaultEventLoop.AddDelayedTask(d, task)
}
func AddPlannedTask(t time.Time, task func(ctx Context)) chrono.Timer {
return DefaultEventLoop.AddPlannedTask(t, task)
}
func NewEventLoop(clock chrono.Clock) *eventLoopT {
return &eventLoopT{
clock: clock,
}
}
type eventLoopT struct {
clock chrono.Clock
}
var _ EventLoop = &eventLoopT{}
func (e *eventLoopT) Clock() chrono.Clock {
return e.clock
}
func (e *eventLoopT) AddTask(task func(ctx Context)) chrono.Timer {
return e.AddDelayedTask(0, task)
}
func (e *eventLoopT) AddDelayedTask(d time.Duration, task func(ctx Context)) chrono.Timer {
c := MakeCoroutine(e, task)
timer := e.clock.AfterFunc(d, func(now time.Time) { c() })
return timer
}
func (e *eventLoopT) AddPlannedTask(t time.Time, task func(ctx Context)) chrono.Timer {
c := MakeCoroutine(e, task)
timer := e.clock.UntilFunc(t, func(now time.Time) { c() })
return timer
}
func (e *eventLoopT) AddPlannedTaskCtx(ctx context.Context, t time.Time, task func(ctx Context)) {
ctx, cancel := context.WithCancel(ctx)
var once sync.Once
taskOnce := func(ctx Context) {
once.Do(func() {
cancel()
task(ctx)
})
}
e.AddPlannedTask(t, taskOnce)
go func() {
<-ctx.Done()
e.AddTask(taskOnce)
}()
}