This commit is contained in:
2026-08-16 15:11:38 +08:00
parent f7f6db8695
commit a85477be80
40 changed files with 761 additions and 144 deletions
+15 -1
View File
@@ -34,7 +34,7 @@ type scheduledEntry struct {
}
func NewTaskScheduler(tasks *biz.TaskUsecase, authorities *biz.AuthorityUsecase, executor *TaskExecutor, logger *slog.Logger) *TaskScheduler {
return &TaskScheduler{tasks: tasks, authorities: authorities, executor: executor, logger: logger, standard: cron.New(), seconds: cron.New(cron.WithSeconds()), entries: map[uint]scheduledEntry{}, subscribers: map[uint]map[chan []byte]struct{}{}}
return &TaskScheduler{tasks: tasks, authorities: authorities, executor: executor, logger: logger.With("mod", "timedTask"), standard: cron.New(), seconds: cron.New(cron.WithSeconds()), entries: map[uint]scheduledEntry{}, subscribers: map[uint]map[chan []byte]struct{}{}}
}
func NewTaskRuntime(scheduler *TaskScheduler) biz.TaskRuntime { return scheduler }
@@ -48,13 +48,17 @@ func (s *TaskScheduler) Start(ctx context.Context) error {
s.seconds.Start()
items, _, err := s.tasks.ListTasks(ctx, 0, 0, nil)
if err == nil {
loaded := 0
for _, task := range items {
if task.Enabled {
if scheduleErr := s.Schedule(task); scheduleErr != nil {
s.logger.ErrorContext(ctx, "restore timed task failed", "id", task.ID, "error", scheduleErr)
} else {
loaded++
}
}
}
s.logger.InfoContext(ctx, "定时任务加载完成", "task_count", loaded)
} else {
s.logger.WarnContext(ctx, "timed task table is not ready", "error", err)
}
@@ -117,6 +121,7 @@ func (s *TaskScheduler) Reload(ctx context.Context) error {
}
}
}
s.logger.InfoContext(ctx, "定时任务重载完成", "task_count", len(items))
return nil
}
@@ -131,6 +136,15 @@ func (s *TaskScheduler) executionContext() context.Context {
func (s *TaskScheduler) run(task *biz.TimedTask, trigger string) {
log := s.executor.Run(s.executionContext(), task, trigger)
attributes := []any{"task_id", log.TaskID, "task_name", log.TaskName, "trigger_type", log.TriggerType, "status", log.Status, "duration_ms", log.DurationMS, "started_at", log.StartedAt, "finished_at", log.FinishedAt}
if log.ErrorMsg != "" {
attributes = append(attributes, "error", log.ErrorMsg)
}
if log.Status == "success" {
s.logger.Info("timed task finished", attributes...)
} else {
s.logger.Error("timed task finished", attributes...)
}
if log.Status != "success" {
ids, err := s.authorities.AuthorityUserIDs(context.Background(), 888)
if err != nil {