2018-05-26 16:21:23 +00:00
|
|
|
|
|
|
|
#include "AsyncTask.h"
|
|
|
|
|
2018-05-28 14:19:04 +00:00
|
|
|
AsyncTask::AsyncTask()
|
|
|
|
: QObject(nullptr),
|
2018-05-26 18:09:20 +00:00
|
|
|
QRunnable()
|
|
|
|
{
|
2018-05-28 14:19:04 +00:00
|
|
|
setAutoDelete(false);
|
2018-05-26 18:09:20 +00:00
|
|
|
running = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
AsyncTask::~AsyncTask()
|
|
|
|
{
|
|
|
|
wait();
|
|
|
|
}
|
|
|
|
|
|
|
|
void AsyncTask::wait()
|
|
|
|
{
|
|
|
|
runningMutex.lock();
|
|
|
|
runningMutex.unlock();
|
|
|
|
}
|
|
|
|
|
|
|
|
bool AsyncTask::wait(int timeout)
|
|
|
|
{
|
|
|
|
bool r = runningMutex.tryLock(timeout);
|
|
|
|
if (r) {
|
|
|
|
runningMutex.unlock();
|
|
|
|
}
|
|
|
|
return r;
|
|
|
|
}
|
|
|
|
|
|
|
|
void AsyncTask::interrupt()
|
|
|
|
{
|
|
|
|
interrupted = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
void AsyncTask::prepareRun()
|
|
|
|
{
|
|
|
|
interrupted = false;
|
|
|
|
wait();
|
2018-05-27 14:51:01 +00:00
|
|
|
timer.start();
|
2018-05-26 18:09:20 +00:00
|
|
|
}
|
|
|
|
|
2018-05-26 16:21:23 +00:00
|
|
|
void AsyncTask::run()
|
|
|
|
{
|
2018-05-26 18:09:20 +00:00
|
|
|
runningMutex.lock();
|
2018-05-28 14:19:04 +00:00
|
|
|
|
2018-05-26 18:09:20 +00:00
|
|
|
running = true;
|
2018-05-28 14:19:04 +00:00
|
|
|
|
2018-05-26 18:49:57 +00:00
|
|
|
logBuffer = "";
|
|
|
|
emit logChanged(logBuffer);
|
2018-05-26 16:21:23 +00:00
|
|
|
runTask();
|
2018-05-28 14:19:04 +00:00
|
|
|
|
2018-05-26 18:09:20 +00:00
|
|
|
running = false;
|
2018-05-28 14:19:04 +00:00
|
|
|
|
|
|
|
emit finished();
|
|
|
|
|
2018-05-26 18:09:20 +00:00
|
|
|
runningMutex.unlock();
|
2018-05-26 16:21:23 +00:00
|
|
|
}
|
|
|
|
|
2018-05-26 18:49:57 +00:00
|
|
|
void AsyncTask::log(QString s)
|
|
|
|
{
|
|
|
|
logBuffer += s;
|
|
|
|
emit logChanged(logBuffer);
|
|
|
|
}
|
|
|
|
|
2018-05-26 16:21:23 +00:00
|
|
|
AsyncTaskManager::AsyncTaskManager(QObject *parent)
|
|
|
|
: QObject(parent)
|
|
|
|
{
|
|
|
|
threadPool = new QThreadPool(this);
|
|
|
|
}
|
|
|
|
|
|
|
|
AsyncTaskManager::~AsyncTaskManager()
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2018-05-28 14:19:04 +00:00
|
|
|
void AsyncTaskManager::start(AsyncTask::Ptr task)
|
2018-05-26 16:21:23 +00:00
|
|
|
{
|
2018-05-28 14:19:04 +00:00
|
|
|
tasks.append(task);
|
2018-05-26 18:09:20 +00:00
|
|
|
task->prepareRun();
|
2018-05-28 14:19:04 +00:00
|
|
|
|
|
|
|
QWeakPointer<AsyncTask> weakPtr = task;
|
|
|
|
connect(task.data(), &AsyncTask::finished, this, [this, weakPtr]() {
|
|
|
|
tasks.removeOne(weakPtr);
|
2018-06-22 18:34:25 +00:00
|
|
|
emit tasksChanged();
|
2018-05-28 14:19:04 +00:00
|
|
|
});
|
|
|
|
threadPool->start(task.data());
|
2018-06-22 18:34:25 +00:00
|
|
|
emit tasksChanged();
|
|
|
|
}
|
|
|
|
|
|
|
|
bool AsyncTaskManager::getTasksRunning()
|
|
|
|
{
|
|
|
|
return !tasks.isEmpty();
|
2018-05-26 16:21:23 +00:00
|
|
|
}
|