-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskExecutor.cpp
More file actions
78 lines (65 loc) · 1.54 KB
/
Copy pathTaskExecutor.cpp
File metadata and controls
78 lines (65 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "TaskExecutor.hpp"
TaskExecutor::TaskExecutor(QObject *parent)
: QObject(parent), currentIndex(0), running(false) {
timer.setSingleShot(true);
connect(&timer, &QTimer::timeout, this, &TaskExecutor::executeNextTask);
}
void TaskExecutor::setTasks(const QList<Task> &newTasks) {
if (running) {
stop();
}
tasks = newTasks;
currentIndex = 0;
}
void TaskExecutor::addTask(const QString &command, const int intervalMs) {
Task task;
task.command = command;
task.interval = intervalMs > 0 ? intervalMs : 1; // 最小 1ms,避免异常值
tasks.append(task);
}
void TaskExecutor::clearTasks() {
if (running) {
stop();
}
tasks.clear();
currentIndex = 0;
}
void TaskExecutor::start() {
if (running || tasks.isEmpty()) {
return;
}
running = true;
currentIndex = 0;
executeNextTask(); // 第一个任务立即执行
}
void TaskExecutor::stop() {
if (!running) {
return;
}
timer.stop();
running = false;
currentIndex = 0;
emit finished();
}
bool TaskExecutor::isRunning() const { return running; }
void TaskExecutor::executeNextTask() {
if (!running) {
return;
}
if (currentIndex >= tasks.size()) {
timer.stop();
running = false;
emit finished();
return;
}
const Task currentTask = tasks.at(currentIndex);
emit taskExecuted(currentTask.command);
currentIndex++;
if (currentIndex < tasks.size()) {
const int nextDelayMs = currentTask.interval > 0 ? currentTask.interval : 1;
timer.start(nextDelayMs);
} else {
running = false;
emit finished();
}
}