-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis_scheduler.go
191 lines (153 loc) · 4.16 KB
/
redis_scheduler.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package goscheds
import (
"context"
"encoding/json"
"fmt"
"github.com/google/uuid"
"sync"
"time"
"github.com/bsm/redislock"
"github.com/cenkalti/backoff/v4"
"github.com/go-redis/redis/v9"
log "github.com/sirupsen/logrus"
)
type RedisScheduler struct {
namespace string
client *redis.Client
locker *redislock.Client
*sync.Mutex
}
var _ SchedulerService = (*RedisScheduler)(nil)
func NewRedisScheduler(namespace string, client *redis.Client) *RedisScheduler {
redisLocker := redislock.New(client)
return &RedisScheduler{
namespace: namespace,
locker: redisLocker,
client: client,
Mutex: &sync.Mutex{},
}
}
//RegisterHandler will register handler to the
const (
scheduledKeyName = "scheduled_task"
)
//Push will push a job right away to work queue, ExecuteAt field will be ignored
func (r *RedisScheduler) Push(ctx context.Context, job *Job) error {
job.Id = uuid.NewString()
return r.addItemToWorkQueue(ctx, job)
}
//PushScheduled will push job to a queue. A handler for pushed must
//be registered before pushing job to the queue
func (r *RedisScheduler) PushScheduled(ctx context.Context, job *Job) error {
job.Id = uuid.NewString()
log.Debugf("pushing job %s args %s", job.JobName, job.Args)
jobB, err := job.marshal()
if err != nil {
log.Error(err)
return err
}
if job.isReadyToExecute() {
lockKey := fmt.Sprintf("%s:LOCK:%s", r.namespace, scheduledKeyName)
locker, err := r.locker.Obtain(ctx, lockKey, 100*time.Millisecond, nil)
if err != nil {
log.Error(err)
return err
}
pushOps := func() error {
if err := r.addItemToWorkQueue(ctx, job); err != nil {
log.Error(err)
}
return err
}
err = backoff.Retry(pushOps, backoff.NewConstantBackOff(time.Millisecond))
if err != nil {
locker.Release(ctx)
log.Error(err)
return err
}
locker.Release(ctx)
return nil
}
key := fmt.Sprintf("%s:%s", r.namespace, scheduledKeyName)
secondsFromNow := job.ExecuteAt.Sub(time.Now()).Seconds()
score := float64(time.Now().Unix()) + secondsFromNow
return r.client.ZAdd(ctx, key, redis.Z{
Score: score,
Member: jobB,
}).Err()
}
//StartScheduler will start the scheduling process. This is blocking,
//thus need to be running on its own goroutine
func (r *RedisScheduler) StartScheduler(ctx context.Context) {
key := fmt.Sprintf("%s:LOCK:%s", r.namespace, scheduledKeyName)
for {
time.Sleep(10 * time.Second)
locker, err := r.locker.Obtain(ctx, key, 100*time.Millisecond, nil)
if err != nil {
log.Error(err)
continue
}
res, err := r.getTopList(ctx)
// no item in the list
if res == nil && err == nil {
locker.Release(ctx)
time.Sleep(100 * time.Millisecond)
continue
}
if err != nil {
log.Error(err)
locker.Release(ctx)
continue
}
// check if the task date is match the current date
if res.isReadyToExecute() {
if err := r.deleteFromList(ctx, res); err != nil {
locker.Release(ctx)
log.Error(err)
continue
}
pushOps := func() error {
if err := r.addItemToWorkQueue(ctx, res); err != nil {
log.Error(err)
}
return err
}
err = backoff.Retry(pushOps, backoff.NewConstantBackOff(time.Millisecond))
if err != nil {
locker.Release(ctx)
log.Error(err)
}
} else {
locker.Release(ctx)
}
locker.Release(ctx)
}
}
func (r *RedisScheduler) getTopList(ctx context.Context) (*Job, error) {
key := fmt.Sprintf("%s:%s", r.namespace, scheduledKeyName)
res, err := r.client.ZRange(ctx, key, 0, 0).Result()
if err != nil {
return nil, err
}
if len(res) == 0 {
return nil, nil
}
var job *Job
err = json.Unmarshal([]byte(res[0]), &job)
if err != nil {
return nil, err
}
return job, nil
}
func (r *RedisScheduler) deleteFromList(ctx context.Context, job *Job) error {
key := fmt.Sprintf("%s:%s", r.namespace, scheduledKeyName)
// ignore the error, bcs this must be a valid struct
jobB, _ := job.marshal()
return r.client.ZRem(ctx, key, jobB).Err()
}
func (r *RedisScheduler) addItemToWorkQueue(ctx context.Context, job *Job) error {
key := fmt.Sprintf("%s:%s", r.namespace, job.JobName)
// ignore the error, bcs this must be a valid struct
val, _ := job.marshal()
return r.client.RPush(ctx, key, val).Err()
}