35 lines
577 B
Go
35 lines
577 B
Go
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()
|
|
}
|
|
}
|