feat: 增加定时任务执行后门

This commit is contained in:
fuzhongyun 2026-03-02 17:38:26 +08:00
parent e981115cc1
commit c7b35f8dcd
2 changed files with 46 additions and 0 deletions

View File

@ -13,6 +13,7 @@ func main() {
configPath := flag.String("config", "./config/config.yaml", "Path to configuration file") configPath := flag.String("config", "./config/config.yaml", "Path to configuration file")
onBot := flag.String("bot", "", "bot start") onBot := flag.String("bot", "", "bot start")
cron := flag.String("cron", "", "close") cron := flag.String("cron", "", "close")
runJob := flag.String("runJob", "", "run single job and exit")
flag.Parse() flag.Parse()
ctx := context.Background() ctx := context.Background()
bc, err := config.LoadConfig(*configPath) bc, err := config.LoadConfig(*configPath)
@ -33,6 +34,11 @@ func main() {
if *cron == "start" { if *cron == "start" {
app.Cron.Run(ctx) app.Cron.Run(ctx)
} }
// 运行指定任务并退出
if *runJob != "" {
app.Cron.RunOnce(ctx, *runJob)
return
}
log.Fatal(app.HttpServer.Listen(fmt.Sprintf(":%d", bc.Server.Port))) log.Fatal(app.HttpServer.Listen(fmt.Sprintf(":%d", bc.Server.Port)))
} }

View File

@ -3,6 +3,7 @@ package server
import ( import (
"ai_scheduler/internal/services" "ai_scheduler/internal/services"
"context" "context"
"fmt"
"github.com/gofiber/fiber/v2/log" "github.com/gofiber/fiber/v2/log"
"github.com/robfig/cron/v3" "github.com/robfig/cron/v3"
@ -20,6 +21,7 @@ type cronJob struct {
EntryId int32 EntryId int32
Func func(context.Context) error Func func(context.Context) error
Name string Name string
Key string
Schedule string Schedule string
} }
@ -42,11 +44,13 @@ func (c *CronServer) InitJobs(ctx context.Context) {
{ {
Func: c.cronService.CronReportSendDingTalk, Func: c.cronService.CronReportSendDingTalk,
Name: "直连天下报表推送(钉钉)", Name: "直连天下报表推送(钉钉)",
Key: "ding_report_dingtalk",
Schedule: "20 12,18,23 * * *", Schedule: "20 12,18,23 * * *",
}, },
{ {
Func: c.cronService.CronReportSendQywx, Func: c.cronService.CronReportSendQywx,
Name: "直连天下报表推送(微信)", Name: "直连天下报表推送(微信)",
Key: "ding_report_qywx",
Schedule: "20 12,18,23 * * *", Schedule: "20 12,18,23 * * *",
}, },
} }
@ -96,3 +100,39 @@ func (c *CronServer) Stop() {
c.log.Info("Cron调度器已停止") 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
}