Go Background Automatic Retry Function

Credits to Łukasz Rawa (https://unsplash.com/photos/_4NF4Jppx-c)

Let’s try on Our Code!

package main
import (
...
)
type UserActivitySaver struct { UserEmail string Activity string}func (u *UserActivitySaver) Exec() error { err := SaveToDB(u.UserEmail, u.Activity) if err != nil { return err } return nil}func SaveToDB(email, activity string) error { fmt.Println("SAVING to DB for email", email, " with Activity", activity) time.Sleep(100 * time.Millisecond) if email == "user@test.com" { return errors.New("Mocking an error") } return nil}
func main() {  uas := &UserActivitySaver{    UserEmail: "john@gmail.com",    Activity:  "Login Success",  }  r, err := retrier.New(uas, 5, func(err error) { log.Println("User Activity Saver error", err) })  if err != nil {    log.Fatal("ERR", err)  }  r.Start()  fmt.Println("Start Invocation Done")  time.Sleep(2 * time.Second)  fmt.Println("DONE")}
time sleep 2 seconds just to make sure the main function still alive for the background go routine to finish its job (just a simplification)

Summary

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store