forked from jrallison/go-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheduled.go
75 lines (61 loc) · 1.51 KB
/
scheduled.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package workers
import (
"fmt"
"strings"
"time"
"github.com/go-redis/redis"
)
type scheduled struct {
keys []string
closed chan bool
exit chan bool
}
func (s *scheduled) start() {
go (func() {
for {
select {
case <-s.closed:
return
default:
}
s.poll()
time.Sleep(time.Duration(Config.PollInterval) * time.Second)
}
})()
}
func (s *scheduled) quit() {
close(s.closed)
}
func (s *scheduled) poll() {
// conn := Config.Pool.Get()
// defer conn.Close()
conn := Config.Pool
now := nowToSecondsWithNanoPrecision()
for _, key := range s.keys {
key = Config.Namespace + key
for {
messages, _ := conn.ZRangeByScore(key, &redis.ZRangeBy{
Min: "-inf",
Max: fmt.Sprintf("%.6f", now),
Offset: 0,
Count: 1,
}).Result()
// messages, _ := redis.Strings(conn.Do("zrangebyscore", key, "-inf", now, "limit", 0, 1))
if len(messages) == 0 {
break
}
message, _ := NewMsg(messages[0])
// if removed, _ := redis.Bool(conn.Do("zrem", key, messages[0])); removed {
if removed, _ := conn.ZRem(key, messages[0]).Result(); removed > 0 {
queue, _ := message.Get("queue").String()
queue = strings.TrimPrefix(queue, Config.Namespace)
message.Set("enqueued_at", nowToSecondsWithNanoPrecision())
conn.LPush(Config.Namespace+"queue:"+queue, message.ToJson())
// conn.Do("lpush", Config.Namespace+"queue:"+queue, message.ToJson())
}
}
}
}
func newScheduled(keys ...string) *scheduled {
return &scheduled{keys, make(chan bool), make(chan bool)}
}