How to Implement Delayed and Retry Logic for Jobs in Go

Implement job retries in Go using a manual loop with exponential backoff and time.Sleep since no standard library exists for this.

Go does not have a built-in standard library function for job retries; you must implement a loop with exponential backoff using time.Sleep and time.NewTimer.

func RunWithRetry(job func() error, maxRetries int, initialDelay time.Duration) error {
    delay := initialDelay
    for i := 0; i < maxRetries; i++ {
        if err := job(); err == nil {
            return nil
        }
        time.Sleep(delay)
        delay *= 2 // Exponential backoff
    }
    return fmt.Errorf("job failed after %d retries", maxRetries)
}

To add a delay before the first attempt, call time.Sleep before the loop or use a time.After channel.