Skip to content

Instantly share code, notes, and snippets.

@yinkakun
Created November 22, 2024 15:29
Show Gist options
  • Save yinkakun/ef59d0f405c436d280d75bf8137a5874 to your computer and use it in GitHub Desktop.
Save yinkakun/ef59d0f405c436d280d75bf8137a5874 to your computer and use it in GitHub Desktop.
func retry(maxRetry int, interval time.Duration, f func() error) error {
var error error
for attempt := 0; attempt < maxRetry; attempt++ {
if err := f(); err != nil {
error = err
if attempt < maxRetry-1 {
time.Sleep(interval)
}
continue
}
return nil
}
return fmt.Errorf("operation failed after %d attempts: %w", maxRetry, error)
}
@yinkakun
Copy link
Author

func retry(maxRetry int, interval time.Duration, fn func() error) {
	for attempt := 0; attempt < maxRetry; attempt++ {
		if err := fn(); err == nil {
			return
		}
		time.Sleep(interval)
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment