engine/utils/ticker.go

40 lines
611 B
Go

package utils
import (
"context"
"time"
)
func SetTimeout(f func(), timeout int) context.CancelFunc {
ctx, cancelFunc := context.WithCancel(context.Background())
go func() {
select {
case <-ctx.Done():
case <-time.After(time.Duration(timeout) * time.Second):
f()
}
}()
return cancelFunc
}
func SetInterval(what func(), delay time.Duration) chan bool {
ticker := time.NewTicker(delay)
stopIt := make(chan bool)
go func() {
for {
select {
case <-stopIt:
return
case <-ticker.C:
what()
}
}
}()
// return the bool channel to use it as a stopper
return stopIt
}