- 新增 cron模块,支持定时任务管理- 实现了任务列表获取、任务添加、任务移除和任务状态获取等接口 - 添加了默认任务,包括数据同步、数据清理、健康检查和缓存刷新等 - 实现了优雅关闭功能,确保在服务停止时正确停止所有任务 - 添加了定时任务相关文档和使用指南
114 lines
2.3 KiB
Go
114 lines
2.3 KiB
Go
package cron
|
|
|
|
import (
|
|
"context"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestCronLogic_AddJob(t *testing.T) {
|
|
ctx := context.Background()
|
|
logic := New()
|
|
|
|
// 测试添加任务
|
|
err := logic.AddJob(ctx, "test_job", "* * * * *", func() {
|
|
t.Log("Test job executed")
|
|
})
|
|
|
|
if err != nil {
|
|
t.Errorf("Failed to add job: %v", err)
|
|
}
|
|
|
|
// 测试重复添加同名任务
|
|
err = logic.AddJob(ctx, "test_job", "* * * * *", func() {
|
|
t.Log("Test job executed again")
|
|
})
|
|
|
|
if err == nil {
|
|
t.Error("Expected error when adding duplicate job name")
|
|
}
|
|
|
|
// 清理
|
|
logic.RemoveJob(ctx, "test_job")
|
|
}
|
|
|
|
func TestCronLogic_GetJobStatus(t *testing.T) {
|
|
ctx := context.Background()
|
|
logic := New()
|
|
|
|
// 添加任务
|
|
err := logic.AddJob(ctx, "status_test_job", "* * * * *", func() {
|
|
t.Log("Status test job executed")
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Failed to add job: %v", err)
|
|
}
|
|
|
|
// 测试获取任务状态
|
|
status, err := logic.GetJobStatus(ctx, "status_test_job")
|
|
if err != nil {
|
|
t.Errorf("Failed to get job status: %v", err)
|
|
}
|
|
|
|
if !status {
|
|
t.Error("Expected job to be active")
|
|
}
|
|
|
|
// 测试获取不存在的任务状态
|
|
status, err = logic.GetJobStatus(ctx, "non_existent_job")
|
|
if err != nil {
|
|
t.Errorf("Failed to get non-existent job status: %v", err)
|
|
}
|
|
|
|
if status {
|
|
t.Error("Expected non-existent job to be inactive")
|
|
}
|
|
|
|
// 清理
|
|
logic.RemoveJob(ctx, "status_test_job")
|
|
}
|
|
|
|
func TestCronLogic_RemoveJob(t *testing.T) {
|
|
ctx := context.Background()
|
|
logic := New()
|
|
|
|
// 添加任务
|
|
err := logic.AddJob(ctx, "remove_test_job", "* * * * *", func() {
|
|
t.Log("Remove test job executed")
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Failed to add job: %v", err)
|
|
}
|
|
|
|
// 测试移除任务
|
|
err = logic.RemoveJob(ctx, "remove_test_job")
|
|
if err != nil {
|
|
t.Errorf("Failed to remove job: %v", err)
|
|
}
|
|
|
|
// 测试移除不存在的任务
|
|
err = logic.RemoveJob(ctx, "non_existent_job")
|
|
if err == nil {
|
|
t.Error("Expected error when removing non-existent job")
|
|
}
|
|
}
|
|
|
|
func TestCronLogic_StartStopJobs(t *testing.T) {
|
|
ctx := context.Background()
|
|
logic := New()
|
|
|
|
// 启动任务
|
|
err := logic.StartAllJobs(ctx)
|
|
if err != nil {
|
|
t.Errorf("Failed to start jobs: %v", err)
|
|
}
|
|
|
|
// 等待一段时间让任务执行
|
|
time.Sleep(2 * time.Second)
|
|
|
|
// 停止任务
|
|
err = logic.StopAllJobs(ctx)
|
|
if err != nil {
|
|
t.Errorf("Failed to stop jobs: %v", err)
|
|
}
|
|
} |