📚Cheatsheets

Cheatsheet collection for go, rust, python, shell and javascript.

Repeat execute code every interval

Repeat executes f every interval seconds until stopc is closed. It executes f once right after being called.

import (
	"time"
)

func RepeatExecute(interval time.Duration, stopc <-chan struct{}, f func() error) error {
	tick := time.NewTicker(interval)
	defer tick.Stop()

	for {
		if err := f(); err != nil {
			return err
		}
		select {
		case <-stopc:
			return nil
		case <-tick.C:
		}
	}
}

How to use?

func Run(ctx context.Context, interval time.Duration) error {
	return RepeatExecute(interval, ctx.Done(), func() error {
		 err := someOperation()
		if err != nil {
			return err
		}
		return nil
	})
}