QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
QtRuntimeScheduler.cc
Go to the documentation of this file.
2
3#include <algorithm>
4#include <utility>
5
6#include <QtCore/QTimerEvent>
7
8#include "MonotonicClock.h"
10
11QGC_LOGGING_CATEGORY(QtRuntimeSchedulerLog, "Utilities.Timing.QtRuntimeScheduler")
12
14{
15 qCDebug(QtRuntimeSchedulerLog) << this;
16}
17
19{
20 qCDebug(QtRuntimeSchedulerLog) << this;
21}
22
24{
25 return MonotonicClock::nowUs();
26}
27
28RuntimeScheduler::TaskId QtRuntimeScheduler::schedule(QObject* context, std::chrono::microseconds delay,
29 Callback callback)
30{
31 if (!_canSchedule(context, delay, callback)) {
32 return 0;
33 }
34 const int timer = startTimer((std::max) (delay, std::chrono::microseconds::zero()), Qt::PreciseTimer);
35 if (timer == 0) {
36 return 0;
37 }
38 const auto id = ++_nextTask;
39 const auto contextDestroyed = connect(context, &QObject::destroyed, this, [this, id]() { cancel(id); });
40 _tasks.insert(timer, {id, context, std::move(callback), contextDestroyed});
41 _timers.insert(id, timer);
42 return id;
43}
44
46{
47 if (!_isCurrentThread()) {
48 return;
49 }
50 const auto timer = _timers.find(task);
51 if (timer == _timers.end()) {
52 return;
53 }
54 killTimer(*timer);
55 disconnect(_tasks.take(*timer).contextDestroyed);
56 _timers.erase(timer);
57}
58
59void QtRuntimeScheduler::timerEvent(QTimerEvent* event)
60{
61 const auto found = _tasks.find(event->timerId());
62 if (found == _tasks.end()) {
63 RuntimeScheduler::timerEvent(event);
64 return;
65 }
66 killTimer(found.key());
67 Task task = std::move(*found);
68 _tasks.erase(found);
69 _timers.remove(task.id);
70 disconnect(task.contextDestroyed);
71 if (task.context) {
72 task.callback();
73 }
74}
std::function< void()> Task
#define QGC_LOGGING_CATEGORY(name, categoryStr)
Qt event-loop implementation; no callback runs inside schedule().
void cancel(TaskId task) override
Cancellation from another thread is ignored. All other access and destruction must occur on the owner...
void timerEvent(QTimerEvent *event) override
TaskId schedule(QObject *context, std::chrono::microseconds delay, Callback callback) override
quint64 nowUs() const override
bool _canSchedule(QObject *context, std::chrono::microseconds delay, const Callback &callback) const
bool _isCurrentThread() const
std::function< void()> Callback
uint64_t nowUs()