Skip to content

Instantly share code, notes, and snippets.

@iNetJoJo
Created October 31, 2022 12:46
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save iNetJoJo/9af49ee77bcf9533a1c8049250edf3cd to your computer and use it in GitHub Desktop.
cool util for starting alot of gorutines with error handling
package workload
import (
"context"
"golang.org/x/sync/errgroup"
"time"
)
type Worker func() error
func All(workers []Worker, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
errs, ctx := errgroup.WithContext(ctx)
for _, worker := range workers {
errs.Go(worker)
}
return errs.Wait()
}
type Builder struct {
workers []Worker
}
func NewBuilder() *Builder {
return &Builder{[]Worker{}}
}
func (b *Builder) Add(worker Worker) {
b.workers = append(b.workers, worker)
}
func (b *Builder) RunAll(times ...time.Duration) error {
if len(b.workers) == 0 {
return nil
}
var timeout time.Duration
if len(times) == 0 {
timeout = time.Second * 5
} else {
timeout = times[0]
}
return All(b.workers, timeout)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment