forked from jrallison/go-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheduled.go
66 lines (51 loc) · 1.18 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
package workers
import (
"strings"
"time"
"github.com/garyburd/redigo/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()
now := nowToSecondsWithNanoPrecision()
for _, key := range s.keys {
key = Config.Namespace + key
for {
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 {
queue, _ := message.Get("queue").String()
queue = strings.TrimPrefix(queue, Config.Namespace)
message.Set("enqueued_at", nowToSecondsWithNanoPrecision())
conn.Do("lpush", Config.Namespace+"queue:"+queue, message.ToJson())
}
}
}
conn.Close()
}
func newScheduled(keys ...string) *scheduled {
return &scheduled{keys, make(chan bool), make(chan bool)}
}