-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner.go
81 lines (69 loc) · 2.16 KB
/
runner.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
/*
Package runner helps you to not reinvent the wheel on certain type of applications.
Often you begin your application by starting multiple goroutines to do
separate work. Imagine a server accepting http, tcp, and other protocols.
You probably also create WaitGroups and/or channels to sync these goroutines.
Runner does all that for you.
For examples please view https://github.com/raksly/runner#examples
*/
package runner
import (
"context"
"os"
"os/signal"
"sync"
)
// New creates a new Runner
// Deprecated: Use runner.Runner{}
func New(ctx context.Context) Runner {
return Runner{Ctx: ctx}
}
// Runner runs functions in goroutines with `Run`, `RunContext` and/or
// `RunOtherContext`, returning a channel that is closed when the goroutine
// exits.
// You may wait on all goroutines to finish using `Wait`.
type Runner struct {
// Ctx will be passed to functions called by `RunContext`
Ctx context.Context
wg sync.WaitGroup
}
// Run runs a function of type func() in a new goroutine.
// The returned channel is closed when f returns
func (r *Runner) Run(f func()) <-chan struct{} {
done := make(chan struct{})
r.wg.Add(1)
go func() {
defer func() {
r.wg.Done()
close(done)
}()
f()
}()
return done
}
// RunContext is like `Run`, but passes the context given to `New`.
func (r *Runner) RunContext(f func(context.Context)) <-chan struct{} {
return r.RunOtherContext(r.Ctx, f)
}
// RunOtherContext is like `RunContext`, except you may specify which
// context to be passed to f.
func (r *Runner) RunOtherContext(ctx context.Context, f func(context.Context)) <-chan struct{} {
return r.Run(func() { f(ctx) })
}
// RunSigs is a convenience method to work with OS signals.
// Unlike the other `Run*` functions, the channel returned
// is not closed, but reads the received signal.
func (r *Runner) RunSigs(sigs ...os.Signal) <-chan os.Signal {
sig := make(chan os.Signal, 1)
signal.Notify(sig, sigs...)
return sig
}
// Wait waits for all goroutines started by this runner.
func (r *Runner) Wait() {
r.wg.Wait()
}
// Context returns the context given to `New`.
// Deprecated: Access Runner.Ctx directly.
func (r *Runner) Context() context.Context {
return r.Ctx
}