2020-09-27 08:33:29 +08:00
|
|
|
// Copyright 2020 Kentaro Hibino. All rights reserved.
|
|
|
|
// Use of this source code is governed by a MIT license
|
|
|
|
// that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package asynq
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/hibiken/asynq/internal/base"
|
|
|
|
"github.com/hibiken/asynq/internal/log"
|
|
|
|
)
|
|
|
|
|
|
|
|
// A forwarder is responsible for moving scheduled and retry tasks to pending state
|
|
|
|
// so that the tasks get processed by the workers.
|
|
|
|
type forwarder struct {
|
|
|
|
logger *log.Logger
|
|
|
|
broker base.Broker
|
|
|
|
|
|
|
|
// channel to communicate back to the long running "forwarder" goroutine.
|
|
|
|
done chan struct{}
|
|
|
|
|
|
|
|
// list of queue names to check and enqueue.
|
|
|
|
queues []string
|
|
|
|
|
|
|
|
// poll interval on average
|
|
|
|
avgInterval time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
type forwarderParams struct {
|
|
|
|
logger *log.Logger
|
|
|
|
broker base.Broker
|
|
|
|
queues []string
|
|
|
|
interval time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
func newForwarder(params forwarderParams) *forwarder {
|
|
|
|
return &forwarder{
|
|
|
|
logger: params.logger,
|
|
|
|
broker: params.broker,
|
|
|
|
done: make(chan struct{}),
|
|
|
|
queues: params.queues,
|
|
|
|
avgInterval: params.interval,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-23 21:20:54 +08:00
|
|
|
func (f *forwarder) shutdown() {
|
2020-09-27 08:33:29 +08:00
|
|
|
f.logger.Debug("Forwarder shutting down...")
|
|
|
|
// Signal the forwarder goroutine to stop polling.
|
|
|
|
f.done <- struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// start starts the "forwarder" goroutine.
|
|
|
|
func (f *forwarder) start(wg *sync.WaitGroup) {
|
|
|
|
wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer wg.Done()
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-f.done:
|
|
|
|
f.logger.Debug("Forwarder done")
|
|
|
|
return
|
|
|
|
case <-time.After(f.avgInterval):
|
|
|
|
f.exec()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *forwarder) exec() {
|
2021-03-13 08:23:08 +08:00
|
|
|
if err := f.broker.ForwardIfReady(f.queues...); err != nil {
|
2022-02-17 22:21:26 +08:00
|
|
|
f.logger.Errorf("Failed to forward scheduled tasks: %v", err)
|
2020-09-27 08:33:29 +08:00
|
|
|
}
|
|
|
|
}
|