2
0
mirror of https://github.com/hibiken/asynq.git synced 2024-09-20 11:05:58 +08:00

Gracefully shutdown all scheduled goroutines on (*Launcher).Stop

This commit is contained in:
Ken Hibino 2019-11-19 07:38:09 -08:00
parent 195fd893be
commit e238d3835d
2 changed files with 21 additions and 16 deletions

View File

@ -18,6 +18,7 @@ type manager struct {
// does not exceed the limit // does not exceed the limit
sema chan struct{} sema chan struct{}
// channel to communicate back to the long running "manager" goroutine.
done chan struct{} done chan struct{}
} }
@ -31,7 +32,16 @@ func newManager(rdb *redis.Client, numWorkers int, handler TaskHandler) *manager
} }
func (m *manager) terminate() { func (m *manager) terminate() {
// send a signal to the manager goroutine to stop
// processing tasks from the queue.
m.done <- struct{}{} m.done <- struct{}{}
fmt.Println("--- Waiting for all workers to finish ---")
for i := 0; i < cap(m.sema); i++ {
// block until all workers have released the token
m.sema <- struct{}{}
}
fmt.Println("--- All workers have finished! ----")
} }
func (m *manager) start() { func (m *manager) start() {
@ -39,7 +49,10 @@ func (m *manager) start() {
for { for {
select { select {
case <-m.done: case <-m.done:
m.shutdown() fmt.Println("-------------[Manager]---------------")
fmt.Println("Manager shutting down...")
fmt.Println("-------------------------------------")
return
default: default:
m.processTasks() m.processTasks()
} }
@ -92,10 +105,3 @@ func (m *manager) processTasks() {
} }
}(t) }(t)
} }
func (m *manager) shutdown() {
// TODO(hibiken): implement this. Gracefully shutdown all active goroutines.
fmt.Println("-------------[Manager]---------------")
fmt.Println("Manager shutting down...")
fmt.Println("------------------------------------")
}

View File

@ -13,6 +13,7 @@ import (
type poller struct { type poller struct {
rdb *redis.Client rdb *redis.Client
// channel to communicate back to the long running "poller" goroutine.
done chan struct{} done chan struct{}
// poll interval on average // poll interval on average
@ -23,6 +24,8 @@ type poller struct {
} }
func (p *poller) terminate() { func (p *poller) terminate() {
// send a signal to the manager goroutine to stop
// processing tasks from the queue.
p.done <- struct{}{} p.done <- struct{}{}
} }
@ -31,7 +34,10 @@ func (p *poller) start() {
for { for {
select { select {
case <-p.done: case <-p.done:
p.shutdown() fmt.Println("-------------[Poller]---------------")
fmt.Println("Poller shutting down...")
fmt.Println("------------------------------------")
return
default: default:
p.enqueue() p.enqueue()
time.Sleep(p.avgInterval) time.Sleep(p.avgInterval)
@ -80,10 +86,3 @@ func (p *poller) enqueue() {
} }
} }
} }
func (p *poller) shutdown() {
// TODO(hibiken): implement this. Gracefully shutdown all active goroutines.
fmt.Println("-------------[Poller]---------------")
fmt.Println("Poller shutting down...")
fmt.Println("------------------------------------")
}