-
Notifications
You must be signed in to change notification settings - Fork 343
/
lock.go
72 lines (59 loc) · 1.24 KB
/
lock.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
package main
import (
"fmt"
"os"
"time"
"github.com/go-redis/redis"
"github.com/jasonlvhit/gocron"
)
// Run a Redis instance with Docker: docker run --rm -tid -p 6379:6379 redis:alpine
func lockedTask(name string) {
fmt.Printf("Hello, %s!\n", name)
t := time.NewTicker(time.Millisecond * 100)
c := make(chan struct{})
time.AfterFunc(time.Second*5, func() {
close(c)
})
for {
select {
case <-t.C:
fmt.Print(".")
case <-c:
fmt.Println()
return
}
}
}
// locker implementation with Redis
type locker struct {
cache *redis.Client
}
func (s *locker) Lock(key string) (success bool, err error) {
res, err := s.cache.SetNX(key, time.Now().String(), time.Second*15).Result()
if err != nil {
return false, err
}
return res, nil
}
func (s *locker) Unlock(key string) error {
return s.cache.Del(key).Err()
}
// Run the example in different terminals,
// passing a different name parameter to each
func main() {
// Get a locker
l := &locker{
redis.NewClient(&redis.Options{
Addr: "localhost:6379",
}),
}
// Make locker available for the cron jobs
gocron.SetLocker(l)
arg := "Some Name"
args := os.Args[1:]
if len(args) > 0 {
arg = args[0]
}
gocron.Every(1).Second().Lock().Do(lockedTask, arg)
<-gocron.Start()
}