Last active
April 10, 2022 17:21
-
-
Save dongnguyenltqb/e4308900316acb241216514287e8c9cc to your computer and use it in GitHub Desktop.
go1.18 execute task with retry option
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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