Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 43d2798b41 | |||
| 1beafa934c | |||
| 362d1f455a | |||
| fbb74cdd6d | |||
| 319d6b6db1 | |||
| 3cc3f0400b | |||
| 5793afbab7 | |||
| 30093d0717 | |||
| a4a0d86d74 | |||
| 80bd6b4327 | |||
| b9444c8bb6 | |||
| 0dbd1ee9c2 | |||
| aabce29211 | |||
| 7475f9cd3b | |||
| fabf7f65d7 | |||
| e6915aa766 | |||
| de4a9c8f31 | |||
| 356f843747 | |||
| 52ed316cd1 | |||
| 778bf75650 | |||
| a87fee1f38 | |||
| 1a70738e6d | |||
| c929d1a57d |
+24
-25
@@ -1,26 +1,25 @@
|
|||||||
# You can override the included template(s) by including variable overrides
|
|
||||||
# SAST customization: https://docs.gitlab.com/ee/user/application_security/sast/#customizing-the-sast-settings
|
|
||||||
# Secret Detection customization: https://docs.gitlab.com/ee/user/application_security/secret_detection/#customizing-settings
|
|
||||||
# Dependency Scanning customization: https://docs.gitlab.com/ee/user/application_security/dependency_scanning/#customizing-the-dependency-scanning-settings
|
|
||||||
# Container Scanning customization: https://docs.gitlab.com/ee/user/application_security/container_scanning/#customizing-the-container-scanning-settings
|
|
||||||
# Note that environment variables can be set in several places
|
|
||||||
# See https://docs.gitlab.com/ee/ci/variables/#cicd-variable-precedence
|
|
||||||
stages:
|
stages:
|
||||||
- build
|
- deploy
|
||||||
- test
|
|
||||||
- deploy
|
before_script:
|
||||||
- review
|
- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
|
||||||
- dast
|
- eval $(ssh-agent -s)
|
||||||
- staging
|
- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
|
||||||
- canary
|
- mkdir -p ~/.ssh
|
||||||
- production
|
- chmod 700 ~/.ssh
|
||||||
- incremental rollout 10%
|
- '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
|
||||||
- incremental rollout 25%
|
|
||||||
- incremental rollout 50%
|
deploy_job:
|
||||||
- incremental rollout 100%
|
stage: deploy
|
||||||
- performance
|
script:
|
||||||
- cleanup
|
- git remote remove github || true
|
||||||
sast:
|
- git remote add github git@github.com:yun-ink/timerx.git
|
||||||
stage: test
|
- git remote -v
|
||||||
include:
|
- git checkout master
|
||||||
- template: Auto-DevOps.gitlab-ci.yml
|
- git fsck --full
|
||||||
|
- git prune
|
||||||
|
- git gc --prune=now --aggressive
|
||||||
|
- git push -u github master -f
|
||||||
|
only:
|
||||||
|
- master
|
||||||
|
- tags
|
||||||
+24
-45
@@ -1,4 +1,4 @@
|
|||||||
package timer
|
package timerx
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -10,17 +10,23 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"code.yun.ink/open/timer/lockx"
|
"code.yun.ink/pkg/lockx"
|
||||||
"github.com/go-redis/redis/v8"
|
"github.com/go-redis/redis/v8"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 功能描述
|
||||||
|
// 这是基于Redis的定时任务调度器,能够有效的在服务集群里面调度任务,避免了单点压力过高或单点故障问题
|
||||||
|
// 由于所有的服务代码是一致的,也就是一个定时任务将在所有的服务都有注册,具体调度到哪个服务运行看调度结果
|
||||||
|
|
||||||
|
// 暂不支持删除定时器,因为这个定时器的设计是基于全局的,如果删除了,那么其他服务就不知道了
|
||||||
|
|
||||||
// 单例模式
|
// 单例模式
|
||||||
var clusterOnceLimit sync.Once
|
var clusterOnceLimit sync.Once
|
||||||
|
|
||||||
// 已注册的任务列表
|
// 已注册的任务列表
|
||||||
var clusterWorkerList sync.Map
|
var clusterWorkerList sync.Map
|
||||||
|
|
||||||
type cluster struct {
|
type Cluster struct {
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
redis *redis.Client
|
redis *redis.Client
|
||||||
lockKey string // 全局计算的key
|
lockKey string // 全局计算的key
|
||||||
@@ -29,14 +35,14 @@ type cluster struct {
|
|||||||
listKey string // 可执行的任务列表的key
|
listKey string // 可执行的任务列表的key
|
||||||
}
|
}
|
||||||
|
|
||||||
var clu *cluster = nil
|
var clu *Cluster = nil
|
||||||
|
|
||||||
func InitCluster(ctx context.Context, red *redis.Client) *cluster {
|
func InitCluster(ctx context.Context, red *redis.Client) *Cluster {
|
||||||
clusterOnceLimit.Do(func() {
|
clusterOnceLimit.Do(func() {
|
||||||
clu = &cluster{
|
clu = &Cluster{
|
||||||
ctx: ctx,
|
ctx: ctx,
|
||||||
redis: red,
|
redis: red,
|
||||||
lockKey: "timer:cluster_globalLockKey",
|
lockKey: "timer:cluster_globalLockKey", // 定时器的全局锁
|
||||||
nextKey: "timer:cluster_nextKey",
|
nextKey: "timer:cluster_nextKey",
|
||||||
zsetKey: "timer:cluster_zsetKey",
|
zsetKey: "timer:cluster_zsetKey",
|
||||||
listKey: "timer:cluster_listKey",
|
listKey: "timer:cluster_listKey",
|
||||||
@@ -63,7 +69,7 @@ func InitCluster(ctx context.Context, red *redis.Client) *cluster {
|
|||||||
return clu
|
return clu
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *cluster) AddTimer(ctx context.Context, uniqueKey string, spaceTime time.Duration, callback callback, extend ExtendParams) error {
|
func (c *Cluster) Add(ctx context.Context, uniqueKey string, spaceTime time.Duration, callback callback, extendData interface{}) error {
|
||||||
_, ok := clusterWorkerList.Load(uniqueKey)
|
_, ok := clusterWorkerList.Load(uniqueKey)
|
||||||
if ok {
|
if ok {
|
||||||
return errors.New("key已存在")
|
return errors.New("key已存在")
|
||||||
@@ -86,12 +92,12 @@ func (c *cluster) AddTimer(ctx context.Context, uniqueKey string, spaceTime time
|
|||||||
nowTime := time.Now()
|
nowTime := time.Now()
|
||||||
|
|
||||||
t := timerStr{
|
t := timerStr{
|
||||||
BeginTime: nowTime,
|
BeginTime: nowTime,
|
||||||
NextTime: nowTime,
|
NextTime: nowTime,
|
||||||
SpaceTime: spaceTime,
|
SpaceTime: spaceTime,
|
||||||
Callback: callback,
|
Callback: callback,
|
||||||
Extend: extend,
|
ExtendData: extendData,
|
||||||
UniqueKey: uniqueKey,
|
UniqueKey: uniqueKey,
|
||||||
}
|
}
|
||||||
|
|
||||||
clusterWorkerList.Store(uniqueKey, t)
|
clusterWorkerList.Store(uniqueKey, t)
|
||||||
@@ -119,7 +125,7 @@ func (c *cluster) AddTimer(ctx context.Context, uniqueKey string, spaceTime time
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 计算下一次执行的时间
|
// 计算下一次执行的时间
|
||||||
func (c *cluster) getNextTime() {
|
func (c *Cluster) getNextTime() {
|
||||||
|
|
||||||
// log.Println("begin computer")
|
// log.Println("begin computer")
|
||||||
ctx, cancel := context.WithCancel(c.ctx)
|
ctx, cancel := context.WithCancel(c.ctx)
|
||||||
@@ -184,31 +190,8 @@ func getNextExecTime(beforeTime time.Time, spaceTime time.Duration) time.Time {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 获取任务
|
// 获取任务
|
||||||
func (c *cluster) getTask() {
|
func (c *Cluster) getTask() {
|
||||||
// 定时去Redis获取任务
|
// 定时去Redis获取任务
|
||||||
// zb := redis.ZRangeBy{
|
|
||||||
// Min: "0",
|
|
||||||
// Max: fmt.Sprintf("%+v", time.Now().UnixMilli()),
|
|
||||||
// }
|
|
||||||
|
|
||||||
// taskList, _ := c.redis.ZRangeByScore(c.ctx, c.zsetKey, &zb).Result()
|
|
||||||
|
|
||||||
// if len(taskList) == 0 {
|
|
||||||
// return
|
|
||||||
// }
|
|
||||||
|
|
||||||
// p := c.redis.Pipeline()
|
|
||||||
|
|
||||||
// for _, val := range taskList {
|
|
||||||
// // 添加到可执行队列
|
|
||||||
// p.LPush(c.ctx, c.listKey, val)
|
|
||||||
// // 删除有序集合
|
|
||||||
// p.ZRem(c.ctx, c.zsetKey, val)
|
|
||||||
// }
|
|
||||||
// _, err := p.Exec(c.ctx)
|
|
||||||
// // fmt.Println(err)
|
|
||||||
// _ = err
|
|
||||||
|
|
||||||
script := `
|
script := `
|
||||||
local token = redis.call('zrangebyscore',KEYS[1],ARGV[1],ARGV[2])
|
local token = redis.call('zrangebyscore',KEYS[1],ARGV[1],ARGV[2])
|
||||||
for i,v in ipairs(token) do
|
for i,v in ipairs(token) do
|
||||||
@@ -222,7 +205,7 @@ func (c *cluster) getTask() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 监听任务
|
// 监听任务
|
||||||
func (c *cluster) watch() {
|
func (c *Cluster) watch() {
|
||||||
// 执行任务
|
// 执行任务
|
||||||
for {
|
for {
|
||||||
keys, err := c.redis.BLPop(c.ctx, time.Second*10, c.listKey).Result()
|
keys, err := c.redis.BLPop(c.ctx, time.Second*10, c.listKey).Result()
|
||||||
@@ -236,8 +219,6 @@ func (c *cluster) watch() {
|
|||||||
|
|
||||||
// 执行任务
|
// 执行任务
|
||||||
func doTask(ctx context.Context, red *redis.Client, taskId string) {
|
func doTask(ctx context.Context, red *redis.Client, taskId string) {
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
if err := recover(); err != nil {
|
if err := recover(); err != nil {
|
||||||
@@ -262,8 +243,6 @@ func doTask(ctx context.Context, red *redis.Client, taskId string) {
|
|||||||
}
|
}
|
||||||
defer lock.Unlock()
|
defer lock.Unlock()
|
||||||
|
|
||||||
ctx = context.WithValue(ctx, extendParamKey, t.Extend)
|
|
||||||
|
|
||||||
// 执行任务
|
// 执行任务
|
||||||
t.Callback(ctx)
|
t.Callback(ctx,t.ExtendData)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
package timer
|
package timerx
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
+15
-56
@@ -5,7 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"code.yun.ink/open/timer"
|
"code.yun.ink/pkg/timerx"
|
||||||
"github.com/go-redis/redis/v8"
|
"github.com/go-redis/redis/v8"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -30,7 +30,7 @@ func main() {
|
|||||||
|
|
||||||
func worker() {
|
func worker() {
|
||||||
client := getRedis()
|
client := getRedis()
|
||||||
w := timer.InitWorker(context.Background(), client, &Worker{})
|
w := timerx.InitOnce(context.Background(), client,"test", &Worker{})
|
||||||
w.Add("test", "test", 1*time.Second, map[string]interface{}{
|
w.Add("test", "test", 1*time.Second, map[string]interface{}{
|
||||||
"test": "test",
|
"test": "test",
|
||||||
})
|
})
|
||||||
@@ -52,11 +52,11 @@ func worker() {
|
|||||||
|
|
||||||
type Worker struct{}
|
type Worker struct{}
|
||||||
|
|
||||||
func (w *Worker) Worker(uniqueKey string, jobType string,data map[string]interface{}) timer.WorkerCode {
|
func (w *Worker) Worker(jobType string,uniqueKey string, data interface{}) (timerx.WorkerCode, time.Duration) {
|
||||||
fmt.Println("执行时间:", time.Now().Format("2006-01-02 15:04:05"))
|
fmt.Println("执行时间:", time.Now().Format("2006-01-02 15:04:05"))
|
||||||
fmt.Println(uniqueKey, jobType)
|
fmt.Println(uniqueKey, jobType)
|
||||||
fmt.Println(data)
|
fmt.Println(data)
|
||||||
return timer.WorkerCodeAgain
|
return timerx.WorkerCodeAgain,time.Second
|
||||||
}
|
}
|
||||||
|
|
||||||
func getRedis() *redis.Client {
|
func getRedis() *redis.Client {
|
||||||
@@ -76,63 +76,22 @@ func re() {
|
|||||||
client := getRedis()
|
client := getRedis()
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
cl := timer.InitCluster(ctx, client)
|
cl := timerx.InitCluster(ctx, client)
|
||||||
cl.AddTimer(ctx, "test1", 1*time.Millisecond, aa, timer.ExtendParams{
|
cl.Add(ctx, "test1", 1*time.Millisecond, aa, "data")
|
||||||
Params: map[string]interface{}{
|
cl.Add(ctx, "test2", 1*time.Millisecond, aa, "data")
|
||||||
"test": "text1",
|
cl.Add(ctx, "test3", 1*time.Millisecond, aa, "data")
|
||||||
},
|
cl.Add(ctx, "test4", 1*time.Millisecond, aa, "data")
|
||||||
})
|
cl.Add(ctx, "test5", 1*time.Millisecond, aa, "data")
|
||||||
cl.AddTimer(ctx, "test2", 1*time.Millisecond, aa, timer.ExtendParams{
|
cl.Add(ctx, "test6", 1*time.Millisecond, aa, "data")
|
||||||
Params: map[string]interface{}{
|
|
||||||
"test": "text2",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
cl.AddTimer(ctx, "test3", 1*time.Millisecond, aa, timer.ExtendParams{
|
|
||||||
Params: map[string]interface{}{
|
|
||||||
"test": "text3",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
cl.AddTimer(ctx, "test4", 1*time.Millisecond, aa, timer.ExtendParams{
|
|
||||||
Params: map[string]interface{}{
|
|
||||||
"test": "text4",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
cl.AddTimer(ctx, "test5", 1*time.Millisecond, aa, timer.ExtendParams{
|
|
||||||
Params: map[string]interface{}{
|
|
||||||
"test": "text5",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
cl.AddTimer(ctx, "test6", 1*time.Millisecond, aa, timer.ExtendParams{
|
|
||||||
Params: map[string]interface{}{
|
|
||||||
"test": "text6",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
cl.AddTimer(ctx, "test7", 1*time.Millisecond, aa, timer.ExtendParams{
|
|
||||||
Params: map[string]interface{}{
|
|
||||||
"test": "text7",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
cl.AddTimer(ctx, "test8", 1*time.Millisecond, aa, timer.ExtendParams{
|
|
||||||
Params: map[string]interface{}{
|
|
||||||
"test": "text8",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
cl.AddTimer(ctx, "test9", 1*time.Millisecond, aa, timer.ExtendParams{
|
|
||||||
Params: map[string]interface{}{
|
|
||||||
"test": "text9",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
select {}
|
select {}
|
||||||
}
|
}
|
||||||
|
|
||||||
func aa(ctx context.Context) bool {
|
func aa(ctx context.Context, data interface{}) error {
|
||||||
// fmt.Println(time.Now().Format(time.RFC3339))
|
fmt.Println("执行时间:", time.Now().Format("2006-01-02 15:04:05"))
|
||||||
// fmt.Println("gggggggggggggggggggggggggggg")
|
fmt.Println(data)
|
||||||
a, err := timer.GetExtendParams(ctx)
|
|
||||||
fmt.Printf("%+v %+v \n\n", a, err)
|
|
||||||
time.Sleep(time.Second * 5)
|
time.Sleep(time.Second * 5)
|
||||||
return true
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func d() {
|
func d() {
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
module code.yun.ink/open/timer
|
module code.yun.ink/pkg/timerx
|
||||||
|
|
||||||
go 1.19
|
go 1.19
|
||||||
|
|
||||||
require github.com/go-redis/redis/v8 v8.11.5
|
require github.com/go-redis/redis/v8 v8.11.5
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
code.yun.ink/pkg/lockx v1.0.0 // indirect
|
||||||
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
code.yun.ink/pkg/lockx v1.0.0 h1:xoLyf05PrOAhLID2LbJsEXA8YYURJTK/7spEk/hu/Rs=
|
||||||
|
code.yun.ink/pkg/lockx v1.0.0/go.mod h1:0xUU5xD8fui0Kf7g4TnFmaxUDo59CH2WM+sitko2SLc=
|
||||||
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
|
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
|
||||||
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||||
|
|||||||
-120
@@ -1,120 +0,0 @@
|
|||||||
package lockx
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/go-redis/redis/v8"
|
|
||||||
)
|
|
||||||
|
|
||||||
// 全局锁
|
|
||||||
type globalLock struct {
|
|
||||||
redis *redis.Client
|
|
||||||
ctx context.Context
|
|
||||||
cancel context.CancelFunc
|
|
||||||
uniqueKey string
|
|
||||||
value string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewGlobalLock(ctx context.Context, red *redis.Client, uniqueKey string) *globalLock {
|
|
||||||
ctx, cancel := context.WithTimeout(ctx, time.Second*30)
|
|
||||||
return &globalLock{
|
|
||||||
redis: red,
|
|
||||||
ctx: ctx,
|
|
||||||
cancel: cancel,
|
|
||||||
uniqueKey: uniqueKey,
|
|
||||||
value: fmt.Sprintf("%d", time.Now().UnixNano()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取锁
|
|
||||||
func (g *globalLock) Lock() bool {
|
|
||||||
|
|
||||||
script := `
|
|
||||||
local token = redis.call('get',KEYS[1])
|
|
||||||
if token == false
|
|
||||||
then
|
|
||||||
return redis.call('set',KEYS[1],ARGV[1],'EX',ARGV[2])
|
|
||||||
end
|
|
||||||
return 'ERROR'
|
|
||||||
`
|
|
||||||
|
|
||||||
resp, err := g.redis.Eval(g.ctx, script, []string{g.uniqueKey}, g.value, 5).Result()
|
|
||||||
if resp != "OK" {
|
|
||||||
_ = err
|
|
||||||
log.Println("globalLock Lock", resp, err, g.uniqueKey, g.value)
|
|
||||||
}
|
|
||||||
if resp == "OK" {
|
|
||||||
g.refresh()
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// 尝试获取锁
|
|
||||||
func (g *globalLock) Try(limitTimes int) bool {
|
|
||||||
for i := 0; i < limitTimes; i++ {
|
|
||||||
if g.Lock() {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
time.Sleep(time.Millisecond * 100)
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// 删除锁
|
|
||||||
func (g *globalLock) Unlock() bool {
|
|
||||||
|
|
||||||
script := `
|
|
||||||
local token = redis.call('get',KEYS[1])
|
|
||||||
if token == ARGV[1]
|
|
||||||
then
|
|
||||||
redis.call('del',KEYS[1])
|
|
||||||
return 'OK'
|
|
||||||
end
|
|
||||||
return 'ERROR'
|
|
||||||
`
|
|
||||||
|
|
||||||
resp, err := g.redis.Eval(g.ctx, script, []string{g.uniqueKey}, g.value).Result()
|
|
||||||
if resp != "OK" {
|
|
||||||
log.Println("globalLock Unlock", resp, err, g.uniqueKey, g.value)
|
|
||||||
}
|
|
||||||
g.cancel()
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// 刷新锁
|
|
||||||
func (g *globalLock) refresh() {
|
|
||||||
go func() {
|
|
||||||
t := time.NewTicker(time.Second)
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-t.C:
|
|
||||||
g.refreshExec()
|
|
||||||
case <-g.ctx.Done():
|
|
||||||
t.Stop()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *globalLock) refreshExec() bool {
|
|
||||||
script := `
|
|
||||||
local token = redis.call('get',KEYS[1])
|
|
||||||
if token == ARGV[1]
|
|
||||||
then
|
|
||||||
redis.call('set',KEYS[1],ARGV[1],'EX',ARGV[2])
|
|
||||||
return 'OK'
|
|
||||||
end
|
|
||||||
return 'ERROR'
|
|
||||||
`
|
|
||||||
|
|
||||||
resp, err := g.redis.Eval(g.ctx, script, []string{g.uniqueKey}, g.value, 5).Result()
|
|
||||||
if resp != "OK" {
|
|
||||||
log.Println("globalLock refresh", resp, err, g.uniqueKey, g.value)
|
|
||||||
}
|
|
||||||
return resp == "OK"
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
package lockx_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"code.yun.ink/open/timer/lockx"
|
|
||||||
"github.com/go-redis/redis/v8"
|
|
||||||
)
|
|
||||||
|
|
||||||
var Redis *redis.Client
|
|
||||||
|
|
||||||
// func TestMain(m *testing.M) {
|
|
||||||
// client := redis.NewClient(&redis.Options{
|
|
||||||
// Addr: "127.0.0.1" + ":" + "6379",
|
|
||||||
// Password: "", // no password set
|
|
||||||
// DB: 0, // use default DB
|
|
||||||
// })
|
|
||||||
// if client == nil {
|
|
||||||
// fmt.Println("redis init error")
|
|
||||||
// return
|
|
||||||
// }
|
|
||||||
// // fmt.Println("ffff")
|
|
||||||
// Redis = client
|
|
||||||
// }
|
|
||||||
|
|
||||||
func TestLockx(t *testing.T) {
|
|
||||||
client := redis.NewClient(&redis.Options{
|
|
||||||
Addr: "127.0.0.1" + ":" + "6379",
|
|
||||||
Password: "", // no password set
|
|
||||||
DB: 0, // use default DB
|
|
||||||
})
|
|
||||||
if client == nil {
|
|
||||||
fmt.Println("redis init error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fmt.Println("begin")
|
|
||||||
ctx := context.Background()
|
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
lock := lockx.NewGlobalLock(ctx, client, "lockx:test")
|
|
||||||
|
|
||||||
if !lock.Lock() {
|
|
||||||
fmt.Println("lock error")
|
|
||||||
}
|
|
||||||
defer lock.Unlock()
|
|
||||||
|
|
||||||
fmt.Println("ssss")
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
package timerx
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"runtime/debug"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-redis/redis/v8"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 功能描述
|
||||||
|
// 1. 任务可以多节点发布
|
||||||
|
// 2. 每个任务的执行在全局仅会执行一次
|
||||||
|
// 3. 任务执行失败支持快捷重新加入队列
|
||||||
|
|
||||||
|
// 单次的任务队列
|
||||||
|
type worker struct {
|
||||||
|
ctx context.Context
|
||||||
|
zsetKey string
|
||||||
|
listKey string
|
||||||
|
redis *redis.Client
|
||||||
|
worker Callback
|
||||||
|
}
|
||||||
|
|
||||||
|
type WorkerCode int
|
||||||
|
|
||||||
|
const (
|
||||||
|
WorkerCodeSuccess WorkerCode = 0 // 处理完成(不需要重入)
|
||||||
|
WorkerCodeAgain WorkerCode = -1 // 需要继续定时,默认原来的时间
|
||||||
|
)
|
||||||
|
|
||||||
|
// 需要考虑执行失败重新放入队列的情况
|
||||||
|
type Callback interface {
|
||||||
|
// 任务执行
|
||||||
|
// uniqueKey: 任务唯一标识
|
||||||
|
// jobType: 任务类型,用于区分任务
|
||||||
|
// data: 任务数据
|
||||||
|
Worker(jobType string, uniqueKey string, data interface{}) (WorkerCode, time.Duration)
|
||||||
|
}
|
||||||
|
|
||||||
|
var wo *worker = nil
|
||||||
|
var once sync.Once
|
||||||
|
|
||||||
|
type extendData struct {
|
||||||
|
Delay time.Duration
|
||||||
|
Data interface{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化
|
||||||
|
func InitOnce(ctx context.Context, re *redis.Client, jobGlobalName string, jobCallback Callback) *worker {
|
||||||
|
|
||||||
|
once.Do(func() {
|
||||||
|
wo = &worker{
|
||||||
|
ctx: ctx,
|
||||||
|
zsetKey: "timer:once_zsetkey" + jobGlobalName,
|
||||||
|
listKey: "timer:once_listkey" + jobGlobalName,
|
||||||
|
redis: re,
|
||||||
|
worker: jobCallback,
|
||||||
|
}
|
||||||
|
go wo.getTask()
|
||||||
|
go wo.watch()
|
||||||
|
})
|
||||||
|
|
||||||
|
return wo
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加任务
|
||||||
|
// 重复插入就代表覆盖
|
||||||
|
func (w *worker) Add(jobType string, uniqueKey string, delayTime time.Duration, data interface{}) error {
|
||||||
|
if delayTime.Abs() != delayTime {
|
||||||
|
return fmt.Errorf("时间间隔不能为负数")
|
||||||
|
}
|
||||||
|
if delayTime == 0 {
|
||||||
|
return fmt.Errorf("时间间隔不能为0")
|
||||||
|
}
|
||||||
|
|
||||||
|
redisKey := fmt.Sprintf("%s[:]%s", jobType, uniqueKey)
|
||||||
|
|
||||||
|
ed := extendData{
|
||||||
|
Delay: delayTime,
|
||||||
|
Data: data,
|
||||||
|
}
|
||||||
|
b, _ := json.Marshal(ed)
|
||||||
|
|
||||||
|
_, err := w.redis.SetEX(w.ctx, redisKey, b, delayTime+time.Second*5).Result()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = w.redis.ZAdd(w.ctx, w.zsetKey, &redis.Z{
|
||||||
|
Score: float64(time.Now().Add(delayTime).UnixMilli()),
|
||||||
|
Member: redisKey,
|
||||||
|
}).Result()
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除任务
|
||||||
|
func (w *worker) Del(jobType string, uniqueKey string) error {
|
||||||
|
redisKey := fmt.Sprintf("%s[:]%s", jobType, uniqueKey)
|
||||||
|
|
||||||
|
w.redis.Del(w.ctx, redisKey).Result()
|
||||||
|
|
||||||
|
w.redis.ZRem(w.ctx, w.zsetKey, redisKey).Result()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取任务
|
||||||
|
func (w *worker) getTask() {
|
||||||
|
timer := time.NewTicker(time.Millisecond * 200)
|
||||||
|
defer timer.Stop()
|
||||||
|
|
||||||
|
Loop:
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-timer.C:
|
||||||
|
script := `
|
||||||
|
local token = redis.call('zrangebyscore',KEYS[1],ARGV[1],ARGV[2])
|
||||||
|
for i,v in ipairs(token) do
|
||||||
|
redis.call('zrem',KEYS[1],v)
|
||||||
|
redis.call('lpush',KEYS[2],v)
|
||||||
|
end
|
||||||
|
return "OK"
|
||||||
|
`
|
||||||
|
w.redis.Eval(w.ctx, script, []string{w.zsetKey, w.listKey}, 0, time.Now().UnixMilli()).Result()
|
||||||
|
// fmt.Println(i, err)
|
||||||
|
|
||||||
|
case <-w.ctx.Done():
|
||||||
|
break Loop
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 监听任务
|
||||||
|
func (w *worker) watch() {
|
||||||
|
for {
|
||||||
|
keys, err := w.redis.BLPop(w.ctx, time.Second*10, w.listKey).Result()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("watch err:", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
go w.doTask(keys[1])
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *worker) doTask(key string) {
|
||||||
|
defer func() {
|
||||||
|
if err := recover(); err != nil {
|
||||||
|
fmt.Println("timer:定时器出错", err)
|
||||||
|
log.Println("errStack", string(debug.Stack()))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
s := strings.Split(key, "[:]")
|
||||||
|
|
||||||
|
// 读取数据
|
||||||
|
str, err := w.redis.Get(w.ctx, key).Result()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("execJob err:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ed := extendData{}
|
||||||
|
json.Unmarshal([]byte(str), &ed)
|
||||||
|
|
||||||
|
fmt.Println("开始时间:", time.Now().Format("2006-01-02 15:04:05"))
|
||||||
|
code, t := w.worker.Worker(s[0], s[1], ed.Data)
|
||||||
|
|
||||||
|
if code == WorkerCodeAgain {
|
||||||
|
// 重新放入队列
|
||||||
|
fmt.Println("重入时间:", time.Now().Format("2006-01-02 15:04:05"))
|
||||||
|
if t != 0 && t == t.Abs() {
|
||||||
|
ed.Delay = t
|
||||||
|
}
|
||||||
|
w.Add(s[0], s[1], ed.Delay, ed.Data)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
package timerx
|
||||||
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package timer
|
package timerx
|
||||||
|
|
||||||
// 作者:黄新云
|
// 作者:黄新云
|
||||||
|
|
||||||
@@ -13,30 +13,23 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// 定时器
|
// 定时器
|
||||||
// 原理:每毫秒的时间触发
|
// 1. 这个定时器的作用范围是本机
|
||||||
|
|
||||||
// uuid -> timerStr
|
// uuid -> timerStr
|
||||||
var timerMap = make(map[string]*timerStr)
|
var timerMap = make(map[string]*timerStr)
|
||||||
var timerMapMux sync.Mutex
|
var timerMapMux sync.Mutex
|
||||||
|
|
||||||
var timerCount int // 当前定时数目
|
var timerCount int // 当前定时数目
|
||||||
var onceLimit sync.Once // 实现单例
|
var onceLimit sync.Once // 实现单例
|
||||||
var nextTime = time.Now() // 下一次执行的时间
|
|
||||||
|
|
||||||
type ContextValueKey string // 定义context 传递的Key类型
|
type Single struct{}
|
||||||
|
|
||||||
const (
|
var sin *Single = nil
|
||||||
extendParamKey ContextValueKey = "extend_param"
|
|
||||||
)
|
|
||||||
|
|
||||||
type single struct{}
|
|
||||||
|
|
||||||
var sin *single = nil
|
|
||||||
|
|
||||||
// 定时器类
|
// 定时器类
|
||||||
func InitSingle(ctx context.Context) *single {
|
func InitSingle(ctx context.Context) *Single {
|
||||||
onceLimit.Do(func() {
|
onceLimit.Do(func() {
|
||||||
sin = &single{}
|
sin = &Single{}
|
||||||
|
|
||||||
timer := time.NewTicker(time.Millisecond * 200)
|
timer := time.NewTicker(time.Millisecond * 200)
|
||||||
go func(ctx context.Context) {
|
go func(ctx context.Context) {
|
||||||
@@ -49,7 +42,7 @@ func InitSingle(ctx context.Context) *single {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// 迭代定时器
|
// 迭代定时器
|
||||||
sin.iteratorTimer(ctx, t)
|
sin.iterator(ctx, t)
|
||||||
// fmt.Println("timer: 执行")
|
// fmt.Println("timer: 执行")
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
// 跳出循环
|
// 跳出循环
|
||||||
@@ -64,7 +57,12 @@ func InitSingle(ctx context.Context) *single {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 间隔定时器
|
// 间隔定时器
|
||||||
func (s *single) AddTimer(space time.Duration, call callback, extend ExtendParams) (int, error) {
|
// @param space 间隔时间
|
||||||
|
// @param call 回调函数
|
||||||
|
// @param extend 附加参数
|
||||||
|
// @return int 定时器索引
|
||||||
|
// @return error 错误
|
||||||
|
func (s *Single) Add(space time.Duration, call callback, extend interface{}) (int, error) {
|
||||||
timerMapMux.Lock()
|
timerMapMux.Lock()
|
||||||
defer timerMapMux.Unlock()
|
defer timerMapMux.Unlock()
|
||||||
|
|
||||||
@@ -83,7 +81,7 @@ func (s *single) AddTimer(space time.Duration, call callback, extend ExtendParam
|
|||||||
SpaceTime: space,
|
SpaceTime: space,
|
||||||
CanRunning: make(chan struct{}, 1),
|
CanRunning: make(chan struct{}, 1),
|
||||||
UniqueKey: "",
|
UniqueKey: "",
|
||||||
Extend: extend,
|
ExtendData: extend,
|
||||||
}
|
}
|
||||||
|
|
||||||
timerMap[fmt.Sprintf("%d", timerCount)] = &t
|
timerMap[fmt.Sprintf("%d", timerCount)] = &t
|
||||||
@@ -96,21 +94,15 @@ func (s *single) AddTimer(space time.Duration, call callback, extend ExtendParam
|
|||||||
return timerCount, nil
|
return timerCount, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// 添加需要定时的规则
|
// 删除定时器
|
||||||
func (s *single) AddToTimer(space time.Duration, call callback) int {
|
func (s *Single) Del(index string) {
|
||||||
extend := ExtendParams{}
|
|
||||||
count, _ := s.AddTimer(space, call, extend)
|
|
||||||
return count
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *single) DelToTimer(index string) {
|
|
||||||
timerMapMux.Lock()
|
timerMapMux.Lock()
|
||||||
defer timerMapMux.Unlock()
|
defer timerMapMux.Unlock()
|
||||||
delete(timerMap, index)
|
delete(timerMap, index)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 迭代定时器列表
|
// 迭代定时器列表
|
||||||
func (s *single) iteratorTimer(ctx context.Context, nowTime time.Time) {
|
func (s *Single) iterator(ctx context.Context, nowTime time.Time) {
|
||||||
timerMapMux.Lock()
|
timerMapMux.Lock()
|
||||||
defer timerMapMux.Unlock()
|
defer timerMapMux.Unlock()
|
||||||
|
|
||||||
@@ -159,7 +151,7 @@ func (s *single) iteratorTimer(ctx context.Context, nowTime time.Time) {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
// fmt.Printf("timer: 准备执行 %v %v \n", k, v.Tag)
|
// fmt.Printf("timer: 准备执行 %v %v \n", k, v.Tag)
|
||||||
s.timerAction(ctx, v.Callback, v.UniqueKey, v.Extend)
|
s.doTask(ctx, v.Callback, v.UniqueKey, v.ExtendData)
|
||||||
default:
|
default:
|
||||||
// fmt.Printf("timer: 已在执行 %v %v \n", k, v.Tag)
|
// fmt.Printf("timer: 已在执行 %v %v \n", k, v.Tag)
|
||||||
return
|
return
|
||||||
@@ -182,33 +174,14 @@ func (s *single) iteratorTimer(ctx context.Context, nowTime time.Time) {
|
|||||||
// fmt.Println("timer: one finish")
|
// fmt.Println("timer: one finish")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 定义各个回调函数
|
|
||||||
type callback func(ctx context.Context) bool
|
|
||||||
|
|
||||||
// 定时器操作类
|
// 定时器操作类
|
||||||
// 这里不应painc
|
// 这里不应painc
|
||||||
func (s *single) timerAction(ctx context.Context, call callback, uniqueKey string, extend ExtendParams) bool {
|
func (s *Single) doTask(ctx context.Context, call callback, uniqueKey string, extend interface{}) error {
|
||||||
defer func() {
|
defer func() {
|
||||||
if err := recover(); err != nil {
|
if err := recover(); err != nil {
|
||||||
fmt.Println("timer:定时器出错", err)
|
fmt.Println("timer:定时器出错", err)
|
||||||
log.Println("errStack", string(debug.Stack()))
|
log.Println("errStack", string(debug.Stack()))
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
return call(ctx, extend)
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
// 附加数据
|
|
||||||
ctx = context.WithValue(ctx, extendParamKey, extend)
|
|
||||||
|
|
||||||
return call(ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 快捷方法
|
|
||||||
func GetExtendParams(ctx context.Context) (*ExtendParams, error) {
|
|
||||||
val := ctx.Value(extendParamKey)
|
|
||||||
params, ok := val.(ExtendParams)
|
|
||||||
if !ok {
|
|
||||||
return nil, errors.New("没找到参数")
|
|
||||||
}
|
|
||||||
return ¶ms, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
package timer_test
|
package timerx_test
|
||||||
|
|
||||||
import "testing"
|
import "testing"
|
||||||
|
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
package timer
|
package timerx
|
||||||
|
|
||||||
import "time"
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
type timerStr struct {
|
type timerStr struct {
|
||||||
Callback callback // 需要回调的方法
|
Callback callback // 需要回调的方法
|
||||||
@@ -9,10 +12,12 @@ type timerStr struct {
|
|||||||
NextTime time.Time // [删]下一次执行的时间
|
NextTime time.Time // [删]下一次执行的时间
|
||||||
SpaceTime time.Duration // 任务间隔时间
|
SpaceTime time.Duration // 任务间隔时间
|
||||||
UniqueKey string // 全局唯一键
|
UniqueKey string // 全局唯一键
|
||||||
Extend ExtendParams // 附加参数
|
ExtendData interface{} // 附加参数
|
||||||
}
|
}
|
||||||
|
|
||||||
// 扩展参数
|
|
||||||
type ExtendParams struct {
|
var nextTime = time.Now() // 下一次执行的时间
|
||||||
Params map[string]interface{} // 带出去的参数
|
|
||||||
}
|
|
||||||
|
// 定义各个回调函数
|
||||||
|
type callback func(ctx context.Context, extendData interface{}) error
|
||||||
|
|||||||
@@ -1,159 +0,0 @@
|
|||||||
package timer
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/go-redis/redis/v8"
|
|
||||||
)
|
|
||||||
|
|
||||||
// 单次的任务队列
|
|
||||||
type worker struct {
|
|
||||||
ctx context.Context
|
|
||||||
zsetKey string
|
|
||||||
listKey string
|
|
||||||
redis *redis.Client
|
|
||||||
worker WorkerInterface
|
|
||||||
}
|
|
||||||
|
|
||||||
type WorkerCode int
|
|
||||||
|
|
||||||
const (
|
|
||||||
WorkerCodeSuccess WorkerCode = 0
|
|
||||||
WorkerCodeAgain WorkerCode = -1
|
|
||||||
)
|
|
||||||
|
|
||||||
// 需要考虑执行失败重新放入队列的情况
|
|
||||||
type WorkerInterface interface {
|
|
||||||
Worker(uniqueKey string, jobType string, data map[string]interface{}) WorkerCode
|
|
||||||
}
|
|
||||||
|
|
||||||
var wo *worker = nil
|
|
||||||
var once sync.Once
|
|
||||||
|
|
||||||
type extendData struct {
|
|
||||||
Delay time.Duration
|
|
||||||
Data map[string]interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func InitWorker(ctx context.Context, re *redis.Client, w WorkerInterface) *worker {
|
|
||||||
|
|
||||||
once.Do(func() {
|
|
||||||
wo = &worker{
|
|
||||||
ctx: ctx,
|
|
||||||
zsetKey: "timer:job_zsetkey",
|
|
||||||
listKey: "timer:job_listkey",
|
|
||||||
redis: re,
|
|
||||||
worker: w,
|
|
||||||
}
|
|
||||||
go wo.getTask()
|
|
||||||
go wo.execTask()
|
|
||||||
})
|
|
||||||
|
|
||||||
return wo
|
|
||||||
}
|
|
||||||
|
|
||||||
// 添加任务
|
|
||||||
// 重复插入就代表覆盖
|
|
||||||
func (w *worker) Add(uniqueKey string, jobType string, delayTime time.Duration, data map[string]interface{}) error {
|
|
||||||
if delayTime.Abs() != delayTime {
|
|
||||||
return fmt.Errorf("时间间隔不能为负数")
|
|
||||||
}
|
|
||||||
if delayTime == 0 {
|
|
||||||
return fmt.Errorf("时间间隔不能为0")
|
|
||||||
}
|
|
||||||
|
|
||||||
redisKey := fmt.Sprintf("%s[:]%s", uniqueKey, jobType)
|
|
||||||
|
|
||||||
ed := extendData{
|
|
||||||
Delay: delayTime,
|
|
||||||
Data: data,
|
|
||||||
}
|
|
||||||
b, _ := json.Marshal(ed)
|
|
||||||
|
|
||||||
_, err := w.redis.SetEX(w.ctx, redisKey, b, delayTime+time.Second*5).Result()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = w.redis.ZAdd(w.ctx, w.zsetKey, &redis.Z{
|
|
||||||
Score: float64(time.Now().Add(delayTime).UnixMilli()),
|
|
||||||
Member: redisKey,
|
|
||||||
}).Result()
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// 删除任务
|
|
||||||
func (w *worker) Del(uniqueKey string, jobType string) error {
|
|
||||||
redisKey := fmt.Sprintf("%s[:]%s", uniqueKey, jobType)
|
|
||||||
|
|
||||||
w.redis.Del(w.ctx, redisKey).Result()
|
|
||||||
|
|
||||||
w.redis.ZRem(w.ctx, w.zsetKey, redisKey).Result()
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取任务
|
|
||||||
func (w *worker) getTask() {
|
|
||||||
timer := time.NewTicker(time.Millisecond * 200)
|
|
||||||
defer timer.Stop()
|
|
||||||
|
|
||||||
Loop:
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-timer.C:
|
|
||||||
script := `
|
|
||||||
local token = redis.call('zrangebyscore',KEYS[1],ARGV[1],ARGV[2])
|
|
||||||
for i,v in ipairs(token) do
|
|
||||||
redis.call('zrem',KEYS[1],v)
|
|
||||||
redis.call('lpush',KEYS[2],v)
|
|
||||||
end
|
|
||||||
return "OK"
|
|
||||||
`
|
|
||||||
w.redis.Eval(w.ctx, script, []string{w.zsetKey, w.listKey}, 0, time.Now().UnixMilli()).Result()
|
|
||||||
// fmt.Println(i, err)
|
|
||||||
|
|
||||||
case <-w.ctx.Done():
|
|
||||||
break Loop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 执行任务
|
|
||||||
func (w *worker) execTask() {
|
|
||||||
for {
|
|
||||||
keys, err := w.redis.BLPop(w.ctx, time.Second*10, w.listKey).Result()
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("watch err:", err)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
s := strings.Split(keys[1], "[:]")
|
|
||||||
|
|
||||||
// 读取数据
|
|
||||||
str, err := w.redis.Get(w.ctx, keys[1]).Result()
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("execJob err:", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ed := extendData{}
|
|
||||||
json.Unmarshal([]byte(str), &ed)
|
|
||||||
|
|
||||||
fmt.Println("开始时间:", time.Now().Format("2006-01-02 15:04:05"))
|
|
||||||
code := w.worker.Worker(s[0], s[1], ed.Data)
|
|
||||||
|
|
||||||
if code == WorkerCodeAgain {
|
|
||||||
// 重新放入队列
|
|
||||||
fmt.Println("重入时间:", time.Now().Format("2006-01-02 15:04:05"))
|
|
||||||
w.Add(s[0], s[1], ed.Delay, ed.Data)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user