Skip to content

Commit

Permalink
Worker graceful shutdown (#543)
Browse files Browse the repository at this point in the history
* wait in broker consuming goroutine until worker.Quit() completes

* wait in broker consuming goroutine until worker.Quit() completes for v2
  • Loading branch information
shivanshgaur committed May 11, 2020
1 parent 40440de commit 5d814a4
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
5 changes: 5 additions & 0 deletions v1/worker.go
Expand Up @@ -6,6 +6,7 @@ import (
"net/url"
"os"
"os/signal"
"sync"
"syscall"
"time"

Expand Down Expand Up @@ -69,6 +70,7 @@ func (worker *Worker) LaunchAsync(errorsChan chan<- error) {
log.INFO.Printf(" - PrefetchCount: %d", cnf.AMQP.PrefetchCount)
}

var signalWG sync.WaitGroup
// Goroutine to start broker consumption and handle retries when broker connection dies
go func() {
for {
Expand All @@ -81,6 +83,7 @@ func (worker *Worker) LaunchAsync(errorsChan chan<- error) {
log.WARNING.Printf("Broker failed with error: %s", err)
}
} else {
signalWG.Wait()
errorsChan <- err // stop the goroutine
return
}
Expand All @@ -103,8 +106,10 @@ func (worker *Worker) LaunchAsync(errorsChan chan<- error) {
// After first Ctrl+C start quitting the worker gracefully
log.WARNING.Print("Waiting for running tasks to finish before shutting down")
go func() {
signalWG.Add(1)
worker.Quit()
errorsChan <- ErrWorkerQuitGracefully
signalWG.Done()
}()
} else {
// Abort the program when user hits Ctrl+C second time in a row
Expand Down
5 changes: 5 additions & 0 deletions v2/worker.go
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"

Expand Down Expand Up @@ -63,6 +64,7 @@ func (worker *Worker) LaunchAsync(errorsChan chan<- error) {
log.INFO.Printf(" - PrefetchCount: %d", cnf.AMQP.PrefetchCount)
}

var signalWG sync.WaitGroup
// Goroutine to start broker consumption and handle retries when broker connection dies
go func() {
for {
Expand All @@ -75,6 +77,7 @@ func (worker *Worker) LaunchAsync(errorsChan chan<- error) {
log.WARNING.Printf("Broker failed with error: %s", err)
}
} else {
signalWG.Wait()
errorsChan <- err // stop the goroutine
return
}
Expand All @@ -97,8 +100,10 @@ func (worker *Worker) LaunchAsync(errorsChan chan<- error) {
// After first Ctrl+C start quitting the worker gracefully
log.WARNING.Print("Waiting for running tasks to finish before shutting down")
go func() {
signalWG.Add(1)
worker.Quit()
errorsChan <- errors.New("Worker quit gracefully")
signalWG.Done()
}()
} else {
// Abort the program when user hits Ctrl+C second time in a row
Expand Down

0 comments on commit 5d814a4

Please sign in to comment.