-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrgroup-for-select-pattern.go
63 lines (54 loc) · 1.09 KB
/
errgroup-for-select-pattern.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
package main
import (
"context"
"errors"
"fmt"
"time"
"golang.org/x/sync/errgroup"
)
// errFailure some custom error.
var errFailure = errors.New("some error")
// change test3 to main() before the execution
func test4() {
// Create errgroup with context.
group, qctx := errgroup.WithContext(context.Background())
// Run first periodic task.
//executes second
group.Go(func() error {
fmt.Println("runs first task")
firstTask(qctx)
return nil
})
// Run second task.
//executes first
group.Go(func() error {
fmt.Println("runs second task")
if err := secondTask(); err != nil {
return err
}
return nil
})
// Wait for all tasks to complete or the error to appear.
if err := group.Wait(); err != nil {
fmt.Printf("errgroup tasks ended up with an error: %v", err)
}
}
func firstTask(ctx context.Context) {
var counter int
for {
select {
case <-ctx.Done():
return
case <-time.After(500 * time.Millisecond):
fmt.Println("some task")
if counter > 10 {
return
}
counter++
}
}
}
func secondTask() error {
time.Sleep(7 * time.Second)
return errFailure
}