engine/utils/ticker.go

40 lines
611 B
Go
Raw Permalink Normal View History

2024-02-11 01:31:01 +08:00
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
}