task.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package task
  2. import (
  3. "context"
  4. "time"
  5. )
  6. // TaskStatus 定义任务状态
  7. type TaskStatus string
  8. const (
  9. TaskPending TaskStatus = "pending" // 等待中
  10. TaskRunning TaskStatus = "running" // 运行中
  11. TaskSuccess TaskStatus = "success" // 成功
  12. TaskFailed TaskStatus = "failed" // 失败
  13. TaskCancelled TaskStatus = "cancelled" // 已取消
  14. )
  15. // Task 表示一个可执行任务
  16. type Task struct {
  17. ID string // 任务唯一标识
  18. Type string // 任务类型(如"backup", "repair"等)
  19. Source string // 任务来源(如"mysql:conn1", "redis:conn2"等)
  20. Status TaskStatus // 任务状态
  21. Progress int // 进度百分比 0-100
  22. Result any // 执行结果
  23. Error string // 错误信息
  24. CreatedAt time.Time // 创建时间
  25. StartedAt *time.Time // 开始时间
  26. CompletedAt *time.Time // 完成时间
  27. }
  28. // TaskFunc 定义任务执行函数类型
  29. // progress参数用于更新任务进度(0-100)
  30. type TaskFunc func(ctx context.Context, progress func(int)) (any, error)
  31. // TaskOption 任务选项函数
  32. type TaskOption func(*Task)
  33. // WithSource 设置任务来源
  34. func WithSource(source string) TaskOption {
  35. return func(t *Task) {
  36. t.Source = source
  37. }
  38. }
  39. // WithType 设置任务类型
  40. func WithType(taskType string) TaskOption {
  41. return func(t *Task) {
  42. t.Type = taskType
  43. }
  44. }