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

83 lines
1.7 KiB
Go
Raw Normal View History

2019-11-24 07:22:43 +08:00
package asynq
import (
2019-11-27 22:33:04 +08:00
"fmt"
"log"
2019-11-24 07:44:42 +08:00
"os"
"os/signal"
2019-11-24 07:22:43 +08:00
"sync"
"time"
)
// Background is a top-level entity for the background-task processing.
type Background struct {
mu sync.Mutex
running bool
2019-11-24 07:22:43 +08:00
rdb *rdb
2019-11-24 07:22:43 +08:00
poller *poller
processor *processor
}
// NewBackground returns a new Background instance.
func NewBackground(numWorkers int, opt *RedisOpt) *Background {
2019-11-27 22:41:54 +08:00
rdb := newRDB(opt)
2019-11-24 07:22:43 +08:00
poller := newPoller(rdb, 5*time.Second, []string{scheduled, retry})
processor := newProcessor(rdb, numWorkers, nil)
return &Background{
rdb: rdb,
2019-11-24 07:22:43 +08:00
poller: poller,
processor: processor,
}
}
// TaskHandler handles a given task and reports any error.
type TaskHandler func(*Task) error
2019-11-24 07:44:42 +08:00
// Run starts the background-task processing and blocks until
// an os signal to exit the program is received. Once it receives
// a signal, it gracefully shuts down all pending workers and other
// goroutines to process the tasks.
func (bg *Background) Run(handler TaskHandler) {
bg.start(handler)
defer bg.stop()
// Wait for a signal to exit.
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, os.Kill)
<-sigs
fmt.Println()
log.Println("[INFO] Starting graceful shutdown...")
2019-11-24 07:44:42 +08:00
}
// starts the background-task processing.
func (bg *Background) start(handler TaskHandler) {
2019-11-24 07:22:43 +08:00
bg.mu.Lock()
defer bg.mu.Unlock()
if bg.running {
return
}
2019-11-24 07:22:43 +08:00
bg.running = true
bg.processor.handler = handler
bg.poller.start()
bg.processor.start()
}
2019-11-24 07:44:42 +08:00
// stops the background-task processing.
func (bg *Background) stop() {
2019-11-24 07:22:43 +08:00
bg.mu.Lock()
defer bg.mu.Unlock()
if !bg.running {
return
}
bg.poller.terminate()
bg.processor.terminate()
bg.rdb.client.Close()
bg.processor.handler = nil
bg.running = false
2019-11-24 07:22:43 +08:00
}