2019-11-19 13:23:49 +08:00
|
|
|
package asynq
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/go-redis/redis/v7"
|
|
|
|
)
|
|
|
|
|
|
|
|
type poller struct {
|
2019-11-20 11:44:41 +08:00
|
|
|
rdb *rdb
|
2019-11-19 13:23:49 +08:00
|
|
|
|
2019-11-19 23:38:09 +08:00
|
|
|
// channel to communicate back to the long running "poller" goroutine.
|
2019-11-19 13:23:49 +08:00
|
|
|
done chan struct{}
|
|
|
|
|
|
|
|
// poll interval on average
|
|
|
|
avgInterval time.Duration
|
|
|
|
|
|
|
|
// redis ZSETs to poll
|
|
|
|
zsets []string
|
|
|
|
}
|
|
|
|
|
2019-11-20 11:44:41 +08:00
|
|
|
func newPoller(rdb *rdb, avgInterval time.Duration, zsets []string) *poller {
|
|
|
|
return &poller{
|
|
|
|
rdb: rdb,
|
|
|
|
done: make(chan struct{}),
|
|
|
|
avgInterval: avgInterval,
|
|
|
|
zsets: zsets,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-19 13:23:49 +08:00
|
|
|
func (p *poller) terminate() {
|
2019-11-19 23:38:09 +08:00
|
|
|
// send a signal to the manager goroutine to stop
|
|
|
|
// processing tasks from the queue.
|
2019-11-19 13:23:49 +08:00
|
|
|
p.done <- struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *poller) start() {
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-p.done:
|
2019-11-19 23:38:09 +08:00
|
|
|
fmt.Println("-------------[Poller]---------------")
|
|
|
|
fmt.Println("Poller shutting down...")
|
|
|
|
fmt.Println("------------------------------------")
|
|
|
|
return
|
2019-11-19 22:20:59 +08:00
|
|
|
default:
|
|
|
|
p.enqueue()
|
|
|
|
time.Sleep(p.avgInterval)
|
2019-11-19 13:23:49 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *poller) enqueue() {
|
|
|
|
for _, zset := range p.zsets {
|
|
|
|
// Get next items in the queue with scores (time to execute) <= now.
|
|
|
|
now := time.Now().Unix()
|
|
|
|
fmt.Printf("[DEBUG] polling ZSET %q\n", zset)
|
2019-11-20 11:44:41 +08:00
|
|
|
msgs, err := p.rdb.zRangeByScore(zset,
|
|
|
|
&redis.ZRangeBy{Min: "-inf", Max: strconv.Itoa(int(now))})
|
2019-11-19 13:23:49 +08:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("radis command ZRANGEBYSCORE failed: %v\n", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-11-20 11:44:41 +08:00
|
|
|
for _, m := range msgs {
|
|
|
|
if err := p.rdb.move(zset, m); err != nil {
|
|
|
|
log.Printf("could not move task %+v to queue %q: %v",
|
|
|
|
m, m.Queue, err)
|
2019-11-19 13:23:49 +08:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|