From c7b35f8dcd7d2a0c0f29ff66871a7ed702386aa6 Mon Sep 17 00:00:00 2001 From: fuzhongyun <15339891972@163.com> Date: Mon, 2 Mar 2026 17:38:26 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E5=AE=9A=E6=97=B6?= =?UTF-8?q?=E4=BB=BB=E5=8A=A1=E6=89=A7=E8=A1=8C=E5=90=8E=E9=97=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/server/main.go | 6 ++++++ internal/server/cron.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/cmd/server/main.go b/cmd/server/main.go index bd6b49b..40b9e44 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -13,6 +13,7 @@ func main() { configPath := flag.String("config", "./config/config.yaml", "Path to configuration file") onBot := flag.String("bot", "", "bot start") cron := flag.String("cron", "", "close") + runJob := flag.String("runJob", "", "run single job and exit") flag.Parse() ctx := context.Background() bc, err := config.LoadConfig(*configPath) @@ -33,6 +34,11 @@ func main() { if *cron == "start" { app.Cron.Run(ctx) } + // 运行指定任务并退出 + if *runJob != "" { + app.Cron.RunOnce(ctx, *runJob) + return + } log.Fatal(app.HttpServer.Listen(fmt.Sprintf(":%d", bc.Server.Port))) } diff --git a/internal/server/cron.go b/internal/server/cron.go index 066f357..2bd1c8d 100644 --- a/internal/server/cron.go +++ b/internal/server/cron.go @@ -3,6 +3,7 @@ package server import ( "ai_scheduler/internal/services" "context" + "fmt" "github.com/gofiber/fiber/v2/log" "github.com/robfig/cron/v3" @@ -20,6 +21,7 @@ type cronJob struct { EntryId int32 Func func(context.Context) error Name string + Key string Schedule string } @@ -42,11 +44,13 @@ func (c *CronServer) InitJobs(ctx context.Context) { { Func: c.cronService.CronReportSendDingTalk, Name: "直连天下报表推送(钉钉)", + Key: "ding_report_dingtalk", Schedule: "20 12,18,23 * * *", }, { Func: c.cronService.CronReportSendQywx, Name: "直连天下报表推送(微信)", + Key: "ding_report_qywx", Schedule: "20 12,18,23 * * *", }, } @@ -96,3 +100,39 @@ func (c *CronServer) Stop() { c.log.Info("Cron调度器已停止") } } + +func (c *CronServer) RunOnce(ctx context.Context, key string) error { + + if c.jobs == nil { + c.InitJobs(ctx) + } + + // 获取key对应的任务 + var job *cronJob + for _, j := range c.jobs { + if j.Key == key { + job = j + break + } + } + if job == nil { + return fmt.Errorf("unknown job key: %s\n", key) + } + + defer func() { + if r := recover(); r != nil { + fmt.Printf("任务[once]:%s执行时发生panic: %v\n", job.Name, r) + } + fmt.Printf("任务[once]:%s执行结束\n", job.Name) + }() + + fmt.Printf("任务[once]:%s开始执行\n", job.Name) + + err := job.Func(ctx) + if err != nil { + return fmt.Errorf("任务[once]:%s执行失败: %s\n", job.Name, err.Error()) + } + + fmt.Printf("任务[once]:%s执行成功\n", job.Name) + return nil +}