ForEach runs the provided jobFunc for each job up to concurrency concurrent workers. The execution breaks on first error encountered.
(ctx context.Context, jobs []any, concurrency int, jobFunc func(ctx context.Context, job any) error)
| 61 | // ForEach runs the provided jobFunc for each job up to concurrency concurrent workers. |
| 62 | // The execution breaks on first error encountered. |
| 63 | func ForEach(ctx context.Context, jobs []any, concurrency int, jobFunc func(ctx context.Context, job any) error) error { |
| 64 | if len(jobs) == 0 { |
| 65 | return nil |
| 66 | } |
| 67 | |
| 68 | // Push all jobs to a channel. |
| 69 | ch := make(chan any, len(jobs)) |
| 70 | for _, job := range jobs { |
| 71 | ch <- job |
| 72 | } |
| 73 | close(ch) |
| 74 | |
| 75 | // Start workers to process jobs. |
| 76 | g, ctx := errgroup.WithContext(ctx) |
| 77 | routines := min(concurrency, len(jobs)) |
| 78 | for range routines { |
| 79 | g.Go(func() error { |
| 80 | for job := range ch { |
| 81 | if err := ctx.Err(); err != nil { |
| 82 | return err |
| 83 | } |
| 84 | |
| 85 | if err := jobFunc(ctx, job); err != nil { |
| 86 | return err |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | return nil |
| 91 | }) |
| 92 | } |
| 93 | |
| 94 | // Wait until done (or context has canceled). |
| 95 | return g.Wait() |
| 96 | } |
| 97 | |
| 98 | // CreateJobsFromStrings is a utility to create jobs from an slice of strings. |
| 99 | func CreateJobsFromStrings(values []string) []any { |