-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.go
52 lines (44 loc) · 1.01 KB
/
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
package disq
import (
"context"
"math/rand"
"time"
"github.com/bsm/redislock"
"github.com/go-redis/redis/v8"
)
func Scheduler(name string, c *redis.Client,
fn func(ctx context.Context) (int, error)) {
for {
ctx := context.TODO()
var n int
err := WithRedisLock(ctx, name, c, func(ctx context.Context) error {
var err error
n, err = fn(ctx)
return err
})
if err != nil && err != redislock.ErrNotObtained {
Logger.Printf("redis: %s failed: %s", name, err)
}
if err != nil || n == 0 {
time.Sleep(schedulerBackoff())
}
}
}
func schedulerBackoff() time.Duration {
n := 250 + rand.Intn(250)
return time.Duration(n) * time.Millisecond
}
func WithRedisLock(
ctx context.Context, name string, redis Redis, fn func(ctx context.Context) error,
) error {
lock, err := redislock.Obtain(ctx, redis, name, time.Minute, nil)
if err != nil {
return err
}
defer func() {
if err := lock.Release(ctx); err != nil {
Logger.Printf("redislock.Release failed: %s", err)
}
}()
return fn(ctx)
}