Albert
Loading...
Searching...
No Matches
backgroundexecutor.h
1// SPDX-FileCopyrightText: 2025 Manuel Schneider
2// SPDX-License-Identifier: MIT
3
4#pragma once
5#include <QFutureWatcher>
6#include <QtConcurrentRun>
7#include <atomic>
8#include <functional>
9
10namespace albert
11{
12
20template<typename T>
22{
23 std::unique_ptr<QFutureWatcher<T>> future_watcher_;
24 bool rerun_ = false;
25 std::atomic_bool stop_ = false;
26
27public:
28
34 std::function<T(const bool &abort)> parallel;
35
42 std::function<void()> finish;
43
44
46 BackgroundExecutor() = default;
47
55 {
56 stop_ = true;
57 rerun_ = false;
58 if (future_watcher_ && !future_watcher_->isFinished())
59 future_watcher_->waitForFinished();
60 }
61
68 void run()
69 {
70 if (isRunning())
71 {
72 stop_ = true;
73 rerun_ = true;
74 }
75 else
76 {
77 stop_ = false;
78 rerun_ = false;
79
80 future_watcher_ = std::make_unique<QFutureWatcher<T>>();
81
82 QObject::connect(future_watcher_.get(), &QFutureWatcher<T>::finished,
83 future_watcher_.get(), [this]
84 {
85 if (rerun_)
86 {
87 future_watcher_.reset();
88 run(); // discard results and rerun
89 }
90 else
91 {
92 try {
93 finish(); // may throw
94 } catch (...) {}
95 future_watcher_.reset();
96 }
97 });
98
99 future_watcher_->setFuture(QtConcurrent::run([this]{ return parallel(stop_); }));
100
101 }
102 }
103
105 inline void stop() { stop_ = true; }
106
108 inline bool isRunning() const { return future_watcher_.get(); }
109
111 inline void waitForFinished()
112 {
113 if (future_watcher_)
114 future_watcher_->waitForFinished();
115 }
116
122 inline T takeResult() { return future_watcher_->future().takeResult(); }
123
124};
125
126}
Convenience class for recurring indexing tasks.
Definition backgroundexecutor.h:22
bool isRunning() const
Returns true if the asynchronous computation is currently running; otherwise returns false.
Definition backgroundexecutor.h:108
void waitForFinished()
Blocks until the current task finished.
Definition backgroundexecutor.h:111
~BackgroundExecutor()
Destructs the background executor.
Definition backgroundexecutor.h:54
std::function< T(const bool &abort)> parallel
The task to be executed in a thread.
Definition backgroundexecutor.h:34
void stop()
Stops the current execution.
Definition backgroundexecutor.h:105
std::function< void()> finish
The finish callback.
Definition backgroundexecutor.h:42
void run()
Run or schedule a rerun of the task.
Definition backgroundexecutor.h:68
T takeResult()
Takes the result from the future.
Definition backgroundexecutor.h:122
BackgroundExecutor()=default
Constructs the background executor.
The Albert namespace.
Definition app.h:55