2
0
mirror of https://github.com/hibiken/asynq.git synced 2024-12-25 23:32:17 +08:00

Simplify Background API

This commit is contained in:
Ken Hibino 2019-11-23 15:44:42 -08:00
parent e19c45cff3
commit be3b774b51

View File

@ -1,6 +1,8 @@
package asynq package asynq
import ( import (
"os"
"os/signal"
"sync" "sync"
"time" "time"
@ -32,8 +34,22 @@ func NewBackground(numWorkers int, opt *RedisOpt) *Background {
// TaskHandler handles a given task and reports any error. // TaskHandler handles a given task and reports any error.
type TaskHandler func(*Task) error type TaskHandler func(*Task) error
// Start starts the background-task processing. // Run starts the background-task processing and blocks until
func (bg *Background) Start(handler TaskHandler) { // 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
}
// starts the background-task processing.
func (bg *Background) start(handler TaskHandler) {
bg.mu.Lock() bg.mu.Lock()
defer bg.mu.Unlock() defer bg.mu.Unlock()
if bg.running { if bg.running {
@ -46,8 +62,8 @@ func (bg *Background) Start(handler TaskHandler) {
bg.processor.start() bg.processor.start()
} }
// Stop stops the background-task processing. // stops the background-task processing.
func (bg *Background) Stop() { func (bg *Background) stop() {
bg.mu.Lock() bg.mu.Lock()
defer bg.mu.Unlock() defer bg.mu.Unlock()
if !bg.running { if !bg.running {