Repository navigation
Expand file tree
/
Copy pathexample_test.go
More file actions
67 lines (56 loc) · 1.58 KB
/
Copy pathexample_test.go
File metadata and controls
67 lines (56 loc) · 1.58 KB
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
package runnable_test
import (
"context"
"fmt"
"time"
"github.com/pior/runnable"
)
// JobQueue is a long-running service that processes background jobs.
type JobQueue struct{}
func (q *JobQueue) Run(ctx context.Context) error {
<-ctx.Done()
return nil
}
func (q *JobQueue) Enqueue(job string) {
fmt.Println("JobQueue: " + job)
}
// CleanupTask enqueues a cleanup job on each execution.
type CleanupTask struct {
jobs *JobQueue
runs int
done chan struct{}
}
func (t *CleanupTask) Run(_ context.Context) error {
t.runs++
t.jobs.Enqueue(fmt.Sprintf("cleanup-%d", t.runs))
if t.runs >= 3 {
close(t.done)
}
return nil
}
// The README "Example logs" block copies the output of this example, keep them in sync.
func Example() {
jobs := &JobQueue{}
done := make(chan struct{})
cleanup := &CleanupTask{jobs: jobs, done: done}
m := runnable.NewManager()
m.RegisterService(jobs)
m.RegisterProcess(runnable.Schedule(cleanup, runnable.Every(500*time.Millisecond)))
m.RegisterProcess(runnable.Named("app", runnable.Func(func(_ context.Context) error {
<-done
return nil
})))
runnable.Run(m)
// Output:
// level=INFO msg="manager/JobQueue: started"
// level=INFO msg="manager/schedule/CleanupTask: started"
// level=INFO msg="manager/app: started"
// JobQueue: cleanup-1
// JobQueue: cleanup-2
// JobQueue: cleanup-3
// level=INFO msg="manager/app: stopped"
// level=INFO msg="manager: starting shutdown" reason="app completed"
// level=INFO msg="manager/schedule/CleanupTask: stopped"
// level=INFO msg="manager/JobQueue: stopped"
// level=INFO msg="manager: shutdown complete"
}