Skip to content

Instantly share code, notes, and snippets.

@dongnguyenltqb
Last active April 10, 2022 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dongnguyenltqb/e4308900316acb241216514287e8c9cc to your computer and use it in GitHub Desktop.
Save dongnguyenltqb/e4308900316acb241216514287e8c9cc to your computer and use it in GitHub Desktop.
go1.18 execute task with retry option
package util
type Result[T any] struct {
Error error
Value T
}
type WithRetry[T any] struct {
limit uint
count uint
Result Result[T]
}
func NewWithRetry[T any](limit uint) *WithRetry[T] {
return &WithRetry[T]{
limit: limit,
count: 0,
}
}
func (r *WithRetry[T]) Do(fn func() Result[T]) *WithRetry[T] {
for r.count < r.limit {
r.count += 1
r.Result = fn()
if r.Result.Error == nil {
return r
}
}
return r
}
if r := util.NewWithRetry[int](5).Do(func() util.Result[int] {
var total int
txError := db.Transaction(func(tx *gorm.DB) error {
if err := tx.Raw("select 1+X").Row().Scan(&total); err != nil {
return err
}
return nil
}, &sql.TxOptions{
Isolation: sql.LevelSerializable,
})
return util.Result[int]{
Error: txError,
Value: total,
}
}); r.Result.Error != nil {
panic(r.Result.Error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment