QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
ScheduledTask.cc
Go to the documentation of this file.
1#include "ScheduledTask.h"
2
3#include <utility>
4
6
7QGC_LOGGING_CATEGORY(ScheduledTaskLog, "Utilities.Timing.ScheduledTask")
8
9ScheduledTask::ScheduledTask(RuntimeScheduler* scheduler, QObject* context)
10 : _scheduler(scheduler), _context(context), _state(std::make_shared<State>())
11{
12 qCDebug(ScheduledTaskLog) << this;
13}
14
16{
17 qCDebug(ScheduledTaskLog) << this;
18 cancel();
19}
20
21bool ScheduledTask::schedule(std::chrono::microseconds delay, RuntimeScheduler::Callback callback)
22{
23 cancel();
24 if (!_scheduler || !_context || !callback) {
25 return false;
26 }
27 const auto generation = _state->generation;
28 const std::weak_ptr<State> state = _state;
29 _state->id = _scheduler->schedule(_context, delay, [state, generation, callback = std::move(callback)]() {
30 const auto current = state.lock();
31 if (!current || current->generation != generation) {
32 return;
33 }
34 current->id = 0;
35 callback();
36 });
37 return _state->id != 0;
38}
39
40bool ScheduledTask::scheduleRepeating(std::chrono::microseconds interval, RuntimeScheduler::Callback callback)
41{
42 if (!callback) {
43 cancel();
44 return false;
45 }
46 return schedule(interval, [this, interval, callback = std::move(callback)]() {
47 // Rescheduling replaces this closure, so the run keeps its own copy.
48 const RuntimeScheduler::Callback run = callback;
49 (void) scheduleRepeating(interval, run);
50 run();
51 });
52}
53
55{
56 ++_state->generation;
57 const auto id = std::exchange(_state->id, 0);
58 if (_scheduler && id) {
59 _scheduler->cancel(id);
60 }
61}
62
64{
65 return _scheduler && _context && _state->id != 0;
66}
static std::atomic< jobject > _context
#define QGC_LOGGING_CATEGORY(name, categoryStr)
std::function< void()> Callback
bool scheduleRepeating(std::chrono::microseconds interval, RuntimeScheduler::Callback callback)
bool schedule(std::chrono::microseconds delay, RuntimeScheduler::Callback callback)
bool active() const