@@ -72,7 +72,8 @@ type BasicHost struct {
72
72
73
73
proc goprocess.Process
74
74
75
- bgcancel func ()
75
+ ctx context.Context
76
+ cancel func ()
76
77
mx sync.Mutex
77
78
lastAddrs []ma.Multiaddr
78
79
}
@@ -171,8 +172,8 @@ func NewHost(ctx context.Context, net inet.Network, opts *HostOpts) (*BasicHost,
171
172
net .SetStreamHandler (h .newStreamHandler )
172
173
173
174
bgctx , cancel := context .WithCancel (ctx )
174
- h .bgcancel = cancel
175
- go h . background ( bgctx )
175
+ h .ctx = bgctx
176
+ h . cancel = cancel
176
177
177
178
return h , nil
178
179
}
@@ -214,6 +215,11 @@ func New(net inet.Network, opts ...interface{}) *BasicHost {
214
215
return h
215
216
}
216
217
218
+ // Start starts background tasks in the host
219
+ func (h * BasicHost ) Start () {
220
+ go h .background ()
221
+ }
222
+
217
223
// newConnHandler is the remote-opened conn handler for inet.Network
218
224
func (h * BasicHost ) newConnHandler (c inet.Conn ) {
219
225
// Clear protocols on connecting to new peer to avoid issues caused
@@ -288,10 +294,7 @@ func (h *BasicHost) PushIdentify() {
288
294
}
289
295
}
290
296
291
- func (h * BasicHost ) background (ctx context.Context ) {
292
- // wait a bit for the host to initialize (avoid race with libp2p constructor)
293
- time .Sleep (1 * time .Second )
294
-
297
+ func (h * BasicHost ) background () {
295
298
// periodically schedules an IdentifyPush to update our peers for changes
296
299
// in our address set (if needed)
297
300
ticker := time .NewTicker (1 * time .Minute )
@@ -309,7 +312,7 @@ func (h *BasicHost) background(ctx context.Context) {
309
312
case <- ticker .C :
310
313
h .PushIdentify ()
311
314
312
- case <- ctx .Done ():
315
+ case <- h . ctx .Done ():
313
316
return
314
317
}
315
318
}
@@ -719,7 +722,7 @@ func (h *BasicHost) AllAddrs() []ma.Multiaddr {
719
722
720
723
// Close shuts down the Host's services (network, etc).
721
724
func (h * BasicHost ) Close () error {
722
- h .bgcancel ()
725
+ h .cancel ()
723
726
return h .proc .Close ()
724
727
}
725
728
0 commit comments