Skip to content

Commit 7bf89a7

Browse files
authored
refactor: reuse timers instead of time.After in loops (#687)
Closes #122
1 parent 30abd55 commit 7bf89a7

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

bitswap/network/ipfs_impl.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,10 +179,13 @@ func (s *streamMessageSender) multiAttempt(ctx context.Context, fn func() error)
179179
return err
180180
}
181181

182+
timer := time.NewTimer(s.opts.SendErrorBackoff)
183+
defer timer.Stop()
184+
182185
select {
183186
case <-ctx.Done():
184187
return ctx.Err()
185-
case <-time.After(s.opts.SendErrorBackoff):
188+
case <-timer.C:
186189
// wait a short time in case disconnect notifications are still propagating
187190
log.Infof("send message to %s failed but context was not Done: %s", s.to, err)
188191
}

bootstrap/bootstrap.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -304,15 +304,19 @@ func peersConnect(ctx context.Context, ph host.Host, availablePeers []peer.AddrI
304304
ctx, cancel := context.WithCancel(ctx)
305305
defer cancel()
306306
go func() {
307+
timer := time.NewTimer(time.Second)
308+
defer timer.Stop()
309+
307310
for {
308311
select {
309312
case <-ctx.Done():
310313
return
311-
case <-time.After(1 * time.Second):
314+
case <-timer.C:
312315
if int(atomic.LoadUint64(&connected)) >= needed {
313316
cancel()
314317
return
315318
}
319+
timer.Reset(time.Second)
316320
}
317321
}
318322
}()

mfs/repub.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,18 +169,27 @@ func (rp *Republisher) Run(lastPublished cid.Cid) {
169169

170170
// 2. If we have a value to publish, publish it now.
171171
if toPublish.Defined() {
172+
var timer *time.Timer
172173
for {
173174
err := rp.pubfunc(rp.ctx, toPublish)
174175
if err == nil {
175176
break
176177
}
178+
179+
if timer == nil {
180+
timer = time.NewTimer(rp.RetryTimeout)
181+
defer timer.Stop()
182+
} else {
183+
timer.Reset(rp.RetryTimeout)
184+
}
185+
177186
// Keep retrying until we succeed or we abort.
178187
// TODO(steb): We could try pulling new values
179188
// off `update` but that's not critical (and
180189
// complicates this code a bit). We'll pull off
181190
// a new value on the next loop through.
182191
select {
183-
case <-time.After(rp.RetryTimeout):
192+
case <-timer.C:
184193
case <-rp.ctx.Done():
185194
return
186195
}

0 commit comments

Comments
 (0)