pulse more boilerplate refactoring
This commit is contained in:
34
src/with/every.go
Normal file
34
src/with/every.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package with
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
func GoEvery(ctx context.Context, d time.Duration, foo func()) {
|
||||
every(ctx, d, foo, true)
|
||||
}
|
||||
|
||||
func Every(ctx context.Context, d time.Duration, foo func()) {
|
||||
every(ctx, d, foo, false)
|
||||
}
|
||||
|
||||
func every(ctx context.Context, d time.Duration, foo func(), async bool) {
|
||||
ticker := time.NewTicker(d)
|
||||
defer ticker.Stop()
|
||||
for ctx.Err() == nil {
|
||||
everyTry(ctx, foo, async)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func everyTry(ctx context.Context, foo func(), async bool) {
|
||||
if async {
|
||||
go foo()
|
||||
} else {
|
||||
foo()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user