github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xtime/interval.go (about) 1 package xtime 2 3 import ( 4 "context" 5 "time" 6 ) 7 8 // Interval return a chan chan emit event every duration and a cancel function to cancel interval. 9 func Interval(ctx context.Context, duration time.Duration) (chan struct{}, context.CancelFunc) { 10 ctx, cancel := context.WithCancel(ctx) 11 ch := make(chan struct{}, 1) 12 go func() { 13 ticker := time.NewTicker(duration) 14 for { 15 select { 16 case <-ctx.Done(): 17 close(ch) 18 return 19 case <-ticker.C: 20 ch <- struct{}{} 21 } 22 } 23 }() 24 return ch, cancel 25 } 26 27 // RunInterval run user-defined function every duration until cancel. 28 func RunInterval(ctx context.Context, duration time.Duration, fn func()) context.CancelFunc { 29 ctx, cancel := context.WithCancel(ctx) 30 go func() { 31 ticker := time.NewTicker(duration) 32 for { 33 select { 34 case <-ctx.Done(): 35 return 36 case <-ticker.C: 37 fn() 38 } 39 } 40 }() 41 return cancel 42 }