forked from jrallison/go-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduled.go
62 lines (48 loc) · 1.02 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
package workers
import (
"github.com/garyburd/redigo/redis"
"time"
)
const (
POLL_INTERVAL = 15
)
type scheduled struct {
keys []string
closed bool
exit chan bool
}
func (s *scheduled) start() {
go s.poll(true)
}
func (s *scheduled) quit() {
s.closed = true
}
func (s *scheduled) poll(continuing bool) {
if s.closed {
return
}
conn := Config.Pool.Get()
now := time.Now().Unix()
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()
conn.Do("lpush", Config.namespace+"queue:"+queue, message.ToJson())
}
}
}
conn.Close()
if continuing {
time.Sleep(POLL_INTERVAL * time.Second)
s.poll(true)
}
}
func newScheduled(keys ...string) *scheduled {
return &scheduled{keys, false, make(chan bool)}
}