From d0120ee4840da1a8b7019ed65aa80ab69ff32c87 Mon Sep 17 00:00:00 2001 From: Daniele Vasselli Date: Thu, 21 Mar 2024 15:44:27 +0100 Subject: [PATCH 1/2] Replace the time.After with the timer for efficiency. Signed-off-by: Daniele Vasselli --- client.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/client.go b/client.go index 19b809a..817e664 100644 --- a/client.go +++ b/client.go @@ -799,9 +799,15 @@ func (c *client) Publish(topic string, qos byte, retained bool, payload interfac if publishWaitTimeout == 0 { publishWaitTimeout = time.Second * 30 } + t := time.NewTimer(publishWaitTimeout) + defer func() { + if !t.Stop() { + <-t.C + } + }() select { case c.obound <- &PacketAndToken{p: pub, t: token}: - case <-time.After(publishWaitTimeout): + case <-t.C: token.setError(errors.New("publish was broken by timeout")) } } From 8b638fb7218a29feb2d2450f7bd3892c8cab5507 Mon Sep 17 00:00:00 2001 From: Daniele Vasselli Date: Thu, 21 Mar 2024 21:26:56 +0100 Subject: [PATCH 2/2] Remove the channel draining since it is not reused. Signed-off-by Daniele Vasselli --- client.go | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/client.go b/client.go index 817e664..af5538e 100644 --- a/client.go +++ b/client.go @@ -799,12 +799,10 @@ func (c *client) Publish(topic string, qos byte, retained bool, payload interfac if publishWaitTimeout == 0 { publishWaitTimeout = time.Second * 30 } + t := time.NewTimer(publishWaitTimeout) - defer func() { - if !t.Stop() { - <-t.C - } - }() + defer t.Stop() + select { case c.obound <- &PacketAndToken{p: pub, t: token}: case <-t.C: