2
0
mirror of https://github.com/hibiken/asynq.git synced 2024-11-13 04:46:39 +08:00
asynq/launcher.go

62 lines
1.2 KiB
Go
Raw Normal View History

package asynq
import (
"sync"
"time"
"github.com/go-redis/redis/v7"
)
2019-11-21 12:08:03 +08:00
// Launcher starts the processor and poller.
type Launcher struct {
2019-11-21 12:08:03 +08:00
// running indicates whether processor and poller are both running.
running bool
mu sync.Mutex
poller *poller
2019-11-21 12:08:03 +08:00
processor *processor
}
// NewLauncher creates and returns a new Launcher.
func NewLauncher(poolSize int, opt *RedisOpt) *Launcher {
client := redis.NewClient(&redis.Options{Addr: opt.Addr, Password: opt.Password})
rdb := newRDB(client)
poller := newPoller(rdb, 5*time.Second, []string{scheduled, retry})
2019-11-21 12:08:03 +08:00
processor := newProcessor(rdb, poolSize, nil)
return &Launcher{
poller: poller,
2019-11-21 12:08:03 +08:00
processor: processor,
}
}
// TaskHandler handles a given task and report any error.
type TaskHandler func(*Task) error
2019-11-21 12:08:03 +08:00
// Start starts the processor and poller.
func (l *Launcher) Start(handler TaskHandler) {
l.mu.Lock()
defer l.mu.Unlock()
if l.running {
return
}
l.running = true
2019-11-21 12:08:03 +08:00
l.processor.handler = handler
l.poller.start()
2019-11-21 12:08:03 +08:00
l.processor.start()
}
2019-11-21 12:08:03 +08:00
// Stop stops both processor and poller.
func (l *Launcher) Stop() {
l.mu.Lock()
defer l.mu.Unlock()
if !l.running {
return
}
l.running = false
2019-11-22 12:22:55 +08:00
l.processor.handler = nil
l.poller.terminate()
2019-11-21 12:08:03 +08:00
l.processor.terminate()
}