d2/lib/background/background.go
2023-03-18 15:29:46 -07:00

28 lines
370 B
Go

package background
import "time"
func Repeat(do func(), interval time.Duration) (cancel func()) {
t := time.NewTicker(interval)
done := make(chan struct{})
go func() {
defer t.Stop()
for {
select {
case <-t.C:
do()
case <-done:
return
}
}
}()
stopped := false
return func() {
if !stopped {
stopped = true
close(done)
}
}
}