-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheduler.go
53 lines (48 loc) · 955 Bytes
/
scheduler.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
package stdserver
import (
"context"
"time"
)
type Task func(ctx context.Context)
func (app *App) StartChild(task Task) {
app.lock.RLock()
defer app.lock.RUnlock()
app.children = append(app.children, task)
if app.running {
go task(app.ctx)
}
}
func (app *App) StartChildInterval(interval time.Duration, task, teardown Task) {
app.StartChild(func(ctx context.Context) {
t := time.NewTicker(interval)
outer:
for {
select {
case <-ctx.Done():
break outer
case <-t.C:
task(ctx)
}
}
t.Stop()
if teardown != nil {
// since main ctx is already closed
teardown(context.TODO())
}
})
}
func (app *App) StartChildDelayed(delay time.Duration, task, teardown Task) {
app.StartChild(func(ctx context.Context) {
t := time.NewTimer(delay)
select {
case <-ctx.Done():
case <-t.C:
task(ctx)
}
t.Stop()
if teardown != nil {
// since main ctx is already closed
teardown(context.TODO())
}
})
}