Skip to content

Commit 839942b

Browse files
committed
refactor backoffTimer to normal wait
1 parent 9a1148e commit 839942b

File tree

1 file changed

+5
-29
lines changed

1 file changed

+5
-29
lines changed

tx.go

Lines changed: 5 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,6 @@ func RunInTxContext(ctx context.Context, db BeginTxer, opts *TxOptions, fn func(
6363
option.BackoffDelayFunc = opts.BackoffDelayFunc
6464
}
6565

66-
var backoffTimer *backoffTimer
67-
if option.BackoffDelayFunc != nil {
68-
backoffTimer = newBackoffTimer(option.BackoffDelayFunc)
69-
defer backoffTimer.Stop()
70-
}
71-
7266
f := func() error {
7367
tx, err := db.BeginTx(ctx, &option.TxOptions)
7468
if err != nil {
@@ -94,8 +88,8 @@ func RunInTxContext(ctx context.Context, db BeginTxer, opts *TxOptions, fn func(
9488
return err
9589
}
9690

97-
if backoffTimer != nil && i < option.MaxAttempts-1 {
98-
if err = backoffTimer.Wait(ctx, i); err != nil {
91+
if i < option.MaxAttempts-1 && option.BackoffDelayFunc != nil {
92+
if err = wait(ctx, i, option.BackoffDelayFunc); err != nil {
9993
return err
10094
}
10195
}
@@ -104,34 +98,16 @@ func RunInTxContext(ctx context.Context, db BeginTxer, opts *TxOptions, fn func(
10498
return err
10599
}
106100

107-
type backoffTimer struct {
108-
timer *time.Timer
109-
backOffDelayFunc BackoffDelayFunc
110-
}
111-
112-
func newBackoffTimer(backoffDelayFunc BackoffDelayFunc) *backoffTimer {
113-
return &backoffTimer{
114-
timer: time.NewTimer(0),
115-
backOffDelayFunc: backoffDelayFunc,
116-
}
117-
}
118-
119-
func (b *backoffTimer) Wait(ctx context.Context, attempt int) error {
120-
delay := b.backOffDelayFunc(attempt)
101+
func wait(ctx context.Context, attempt int, backOffDelayFunc BackoffDelayFunc) error {
102+
delay := backOffDelayFunc(attempt)
121103
if delay <= 0 {
122104
return nil
123105
}
124106

125-
b.timer.Reset(delay)
126-
127107
select {
128108
case <-ctx.Done():
129109
return ctx.Err()
130-
case <-b.timer.C:
110+
case <-time.After(delay):
131111
return nil
132112
}
133113
}
134-
135-
func (b *backoffTimer) Stop() bool {
136-
return b.timer.Stop()
137-
}

0 commit comments

Comments
 (0)