2020-01-03 10:13:16 +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.
|
|
|
|
|
2019-12-29 05:33:24 +08:00
|
|
|
package asynq
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/hibiken/asynq/internal/rdb"
|
|
|
|
)
|
|
|
|
|
|
|
|
type scheduler struct {
|
|
|
|
rdb *rdb.RDB
|
|
|
|
|
|
|
|
// channel to communicate back to the long running "scheduler" goroutine.
|
|
|
|
done chan struct{}
|
|
|
|
|
|
|
|
// poll interval on average
|
|
|
|
avgInterval time.Duration
|
2020-01-14 23:26:41 +08:00
|
|
|
|
|
|
|
// list of queues to move the tasks into.
|
|
|
|
qnames []string
|
2019-12-29 05:33:24 +08:00
|
|
|
}
|
|
|
|
|
2020-02-13 14:23:25 +08:00
|
|
|
func newScheduler(r *rdb.RDB, avgInterval time.Duration, qcfg map[string]int) *scheduler {
|
2020-01-14 23:26:41 +08:00
|
|
|
var qnames []string
|
|
|
|
for q := range qcfg {
|
|
|
|
qnames = append(qnames, q)
|
|
|
|
}
|
2019-12-29 05:33:24 +08:00
|
|
|
return &scheduler{
|
|
|
|
rdb: r,
|
|
|
|
done: make(chan struct{}),
|
|
|
|
avgInterval: avgInterval,
|
2020-01-14 23:26:41 +08:00
|
|
|
qnames: qnames,
|
2019-12-29 05:33:24 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *scheduler) terminate() {
|
2020-01-21 23:17:41 +08:00
|
|
|
logger.info("Scheduler shutting down...")
|
2019-12-29 05:33:24 +08:00
|
|
|
// Signal the scheduler goroutine to stop polling.
|
|
|
|
s.done <- struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// start starts the "scheduler" goroutine.
|
|
|
|
func (s *scheduler) start() {
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-s.done:
|
2020-01-21 23:17:41 +08:00
|
|
|
logger.info("Scheduler done")
|
2019-12-29 05:33:24 +08:00
|
|
|
return
|
|
|
|
case <-time.After(s.avgInterval):
|
|
|
|
s.exec()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *scheduler) exec() {
|
2020-01-14 23:26:41 +08:00
|
|
|
if err := s.rdb.CheckAndEnqueue(s.qnames...); err != nil {
|
2020-01-21 23:17:41 +08:00
|
|
|
logger.error("Could not enqueue scheduled tasks: %v", err)
|
2019-12-29 05:33:24 +08:00
|
|
|
}
|
|
|
|
}
|