1 package background 2 3 import "time" 4 5 func Repeat(do func(), interval time.Duration) (cancel func()) { 6 t := time.NewTicker(interval) 7 done := make(chan struct{}) 8 9 go func() { 10 defer t.Stop() 11 for { 12 select { 13 case <-t.C: 14 do() 15 case <-done: 16 return 17 } 18 } 19 }() 20 21 stopped := false 22 return func() { 23 if !stopped { 24 stopped = true 25 close(done) 26 } 27 } 28 } 29