异步定时更新UI #
尽量的减少卡UI问题
//
// Created by 张文兵 on 2025/5/13.
//
#ifndef TASKRUNNER_H
#define TASKRUNNER_H
#include <QFuture>
#include <QElapsedTimer>
#include <QtConcurrent>
#include <atomic>
#include <functional>
#include <QThread>
class TaskRunner {
public:
TaskRunner() = default;
~TaskRunner() { stop(); }
void start(const int intervalMs, const std::function<void()> &task) {
if (m_future.isRunning()) {
return;
}
m_exit = false;
m_future = QtConcurrent::run([=]() {
QElapsedTimer timer;
task(); // 立即执行一次
timer.start();
while (!m_exit) {
if (timer.elapsed() >= intervalMs) {
task(); // 周期执行
timer.restart();
}
if (!m_exit) {
QThread::msleep(100); // 可调精度
}
}
});
}
void stop() {
m_exit = true;
if (m_future.isRunning()) {
m_future.waitForFinished();
}
}
private:
std::atomic<bool> m_exit = false;
QFuture<void> m_future;
};
#endif //TASKRUNNER_H
使用方式 #
// 运行任务
m_taskRunner->start(5000, [this]() {
onUpdateTaskInfo();
});
// 停止任务
m_taskRunner->stop();