Skip to content

Commit 0b9d444

Browse files
author
Justin Azoff
committed
Allow the worker context to interrupt reconnection
1 parent 282153e commit 0b9d444

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

main.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,20 @@ var bufPool = sync.Pool{
4444
},
4545
}
4646

47+
// sleep returns nil after the specified duration or error if interrupted.
48+
// Modified slightly from
49+
// from https://stackoverflow.com/questions/55135239/how-can-i-sleep-with-responsive-context-cancelation
50+
func sleep(ctx context.Context, d time.Duration) error {
51+
t := time.NewTimer(d)
52+
select {
53+
case <-ctx.Done():
54+
t.Stop()
55+
return fmt.Errorf("Interrupted: %w", ctx.Err())
56+
case <-t.C:
57+
}
58+
return nil
59+
}
60+
4761
func receive(conn net.Conn, out chan *bytes.Buffer) {
4862
log.Printf("New connection from %s", conn.RemoteAddr())
4963
defer conn.Close()
@@ -132,7 +146,7 @@ func (w *Worker) ConnectWithRetries(ctx context.Context) error {
132146
if ctx.Err() != nil {
133147
return err
134148
}
135-
time.Sleep(delay)
149+
sleep(ctx, delay)
136150
delay *= 2
137151
if delay > 30*time.Second {
138152
delay = 30 * time.Second

0 commit comments

Comments
 (0)