forked from shunfei/cronsun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
locker.go
47 lines (41 loc) · 820 Bytes
/
locker.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
package cronsun
import (
"time"
client "github.com/coreos/etcd/clientv3"
"github.com/shunfei/cronsun/log"
)
// 任务锁
type locker struct {
kind int
ttl int64
lID client.LeaseID
timer *time.Timer
done chan struct{}
}
func (l *locker) keepAlive() {
duration := time.Duration(l.ttl)*time.Second - 500*time.Millisecond
l.timer = time.NewTimer(duration)
for {
select {
case <-l.done:
return
case <-l.timer.C:
_, err := DefalutClient.KeepAliveOnce(l.lID)
if err != nil {
log.Warnf("lock keep alive err: %s", err.Error())
return
}
l.timer.Reset(duration)
}
}
}
func (l *locker) unlock() {
if l.kind != KindAlone {
return
}
close(l.done)
l.timer.Stop()
if _, err := DefalutClient.Revoke(l.lID); err != nil {
log.Warnf("unlock revoke err: %s", err.Error())
}
}