fix: 修复定时任务关闭不生效问题

This commit is contained in:
TsMask
2025-06-27 11:38:28 +08:00
parent 976d4382dd
commit 0a2d83fd7d
4 changed files with 90 additions and 95 deletions

View File

@@ -1,10 +1,9 @@
package cron
import (
"log"
"testing"
"time"
"be.ems/src/framework/logger"
)
// 参考文章:
@@ -14,13 +13,13 @@ func init() {
StartCron()
}
// 简单示例 队列任务处理
// NewSimple 简单示例 队列任务处理
var NewSimple = &Simple{}
type Simple struct{}
func (s *Simple) Execute(data any) (any, error) {
logger.Infof("执行=> %+v ", data)
log.Printf("执行=> %+v ", data)
// 实现任务处理逻辑
return data, nil
}
@@ -32,7 +31,7 @@ func TestSimple(t *testing.T) {
"ok": "ok",
"data": "data",
}, JobOptions{
JobId: "101",
JobId: 101,
})
simpleC := CreateQueue("simple", NewSimple)
@@ -40,7 +39,7 @@ func TestSimple(t *testing.T) {
"corn": "*/5 * * * * *",
"id": "102",
}, JobOptions{
JobId: "102",
JobId: 102,
Cron: "*/5 * * * * *",
})
@@ -48,7 +47,7 @@ func TestSimple(t *testing.T) {
// "corn": "*/15 * * * * *",
// "id": "103",
// }, JobOptions{
// JobId: "103",
// JobId: 103,
// Cron: "*/15 * * * * *",
// })
@@ -57,7 +56,7 @@ func TestSimple(t *testing.T) {
select {}
}
// Foo 队列任务处理
// NewFooProcessor 等待执行示例 队列任务处理
var NewFooProcessor = &FooProcessor{
progress: 0,
count: 0,
@@ -69,7 +68,7 @@ type FooProcessor struct {
}
func (s *FooProcessor) Execute(data any) (any, error) {
logger.Infof("执行 %d %d => %+v ", s.count, s.progress, data)
log.Printf("执行 %d %d => %+v ", s.count, s.progress, data)
s.count++
// 实现任务处理逻辑
@@ -78,7 +77,7 @@ func (s *FooProcessor) Execute(data any) (any, error) {
for i < 10 {
// 获取任务进度
progress := s.progress
logger.Infof("data: %v => 任务进度:%d", data, progress)
log.Printf("data: %v => 任务进度:%d", data, progress)
// 延迟响应
time.Sleep(time.Second * 2)
i++
@@ -94,21 +93,21 @@ func TestFoo(t *testing.T) {
foo.RunJob(map[string]string{
"data": "2",
}, JobOptions{
JobId: "2",
JobId: 2,
})
fooC := CreateQueue("foo", NewFooProcessor)
fooC.RunJob(map[string]string{
"corn": "*/5 * * * * *",
}, JobOptions{
JobId: "3",
JobId: 3,
Cron: "*/5 * * * * *",
})
select {}
}
// Bar 队列任务处理
// NewBarProcessor 错误中断示例 队列任务处理
var NewBarProcessor = &BarProcessor{
progress: 0,
count: 0,
@@ -120,7 +119,7 @@ type BarProcessor struct {
}
func (s *BarProcessor) Execute(data any) (any, error) {
logger.Infof("执行 %d %d => %+v ", s.count, s.progress, data)
log.Printf("执行 %d %d => %+v ", s.count, s.progress, data)
s.count++
// 实现任务处理逻辑
@@ -129,7 +128,7 @@ func (s *BarProcessor) Execute(data any) (any, error) {
for i < 5 {
// 获取任务进度
progress := s.progress
logger.Infof("data: %v => 任务进度:%d", data, progress)
log.Printf("data: %v => 任务进度:%d", data, progress)
// 延迟响应
time.Sleep(time.Second * 2)
// 程序中途执行错误
@@ -154,14 +153,14 @@ func TestBar(t *testing.T) {
bar.RunJob(map[string]string{
"data": "wdf",
}, JobOptions{
JobId: "81923",
JobId: 752,
})
barC := CreateQueue("bar", NewBarProcessor)
barC.RunJob(map[string]string{
"corn": "*/5 * * * * *",
}, JobOptions{
JobId: "789",
JobId: 756,
Cron: "*/5 * * * * *",
})