Created
October 31, 2022 12:46
Star
You must be signed in to star a gist
cool util for starting alot of gorutines with error handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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