2
0
mirror of https://github.com/hibiken/asynq.git synced 2024-12-27 00:02:19 +08:00
asynq/scheduler.go

70 lines
1.4 KiB
Go
Raw Normal View History

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 (
2020-02-16 15:14:30 +08:00
"sync"
2019-12-29 05:33:24 +08:00
"time"
"github.com/hibiken/asynq/internal/rdb"
)
type scheduler struct {
logger Logger
2020-03-09 22:11:16 +08:00
rdb *rdb.RDB
2019-12-29 05:33:24 +08:00
// channel to communicate back to the long running "scheduler" goroutine.
done chan struct{}
// poll interval on average
avgInterval time.Duration
// list of queues to move the tasks into.
qnames []string
2019-12-29 05:33:24 +08:00
}
func newScheduler(l Logger, r *rdb.RDB, avgInterval time.Duration, qcfg map[string]int) *scheduler {
var qnames []string
for q := range qcfg {
qnames = append(qnames, q)
}
2019-12-29 05:33:24 +08:00
return &scheduler{
2020-03-09 22:11:16 +08:00
logger: l,
2019-12-29 05:33:24 +08:00
rdb: r,
done: make(chan struct{}),
avgInterval: avgInterval,
qnames: qnames,
2019-12-29 05:33:24 +08:00
}
}
func (s *scheduler) terminate() {
2020-03-09 22:11:16 +08:00
s.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.
2020-02-16 15:14:30 +08:00
func (s *scheduler) start(wg *sync.WaitGroup) {
wg.Add(1)
2019-12-29 05:33:24 +08:00
go func() {
2020-02-16 15:14:30 +08:00
defer wg.Done()
2019-12-29 05:33:24 +08:00
for {
select {
case <-s.done:
2020-03-09 22:11:16 +08:00
s.logger.Info("Scheduler done")
2019-12-29 05:33:24 +08:00
return
case <-time.After(s.avgInterval):
s.exec()
}
}
}()
}
func (s *scheduler) exec() {
if err := s.rdb.CheckAndEnqueue(s.qnames...); err != nil {
2020-03-09 22:11:16 +08:00
s.logger.Error("Could not enqueue scheduled tasks: %v", err)
2019-12-29 05:33:24 +08:00
}
}