StartTask attempts to start a new task. It returns an error if a task is already running.
(taskType, groupName string, total int)
| 47 | |
| 48 | // StartTask attempts to start a new task. It returns an error if a task is already running. |
| 49 | func (s *TaskService) StartTask(taskType, groupName string, total int) (*TaskStatus, error) { |
| 50 | currentStatus, err := s.GetTaskStatus() |
| 51 | if err != nil { |
| 52 | return nil, fmt.Errorf("failed to check current task status before starting a new one: %w", err) |
| 53 | } |
| 54 | |
| 55 | if currentStatus.IsRunning { |
| 56 | return nil, errors.New("a task is already running, please wait") |
| 57 | } |
| 58 | |
| 59 | status := &TaskStatus{ |
| 60 | TaskType: taskType, |
| 61 | IsRunning: true, |
| 62 | GroupName: groupName, |
| 63 | Total: total, |
| 64 | Processed: 0, |
| 65 | StartedAt: time.Now(), |
| 66 | } |
| 67 | statusBytes, err := json.Marshal(status) |
| 68 | if err != nil { |
| 69 | return nil, fmt.Errorf("failed to serialize new task status: %w", err) |
| 70 | } |
| 71 | |
| 72 | if err := s.store.Set(globalTaskKey, statusBytes, ResultTTL); err != nil { |
| 73 | return nil, fmt.Errorf("failed to set initial task status: %w", err) |
| 74 | } |
| 75 | |
| 76 | return status, nil |
| 77 | } |
| 78 | |
| 79 | // GetTaskStatus returns the current status of the task. |
| 80 | func (s *TaskService) GetTaskStatus() (*TaskStatus, error) { |
no test coverage detected