game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
task_scheduler.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// task_scheduler.cpp
4// ==============================================================================
5// Background task scheduling system implementation
6// ==============================================================================
7
9
10#include <algorithm>
11#include <atomic>
12#include <condition_variable>
13#include <ctime>
14#include <fstream>
15#include <map>
16#include <mutex>
17#include <random>
18#include <sstream>
19#include <thread>
20
21// ==============================================================================
22// Helper Functions
23// ==============================================================================
24
25namespace
26{
27
28std::string generateUUID()
29{
30 std::random_device rd;
31 std::mt19937 gen(rd());
32 std::uniform_int_distribution<> dis(0, 15);
33 std::uniform_int_distribution<> dis2(8, 11);
34
35 std::stringstream ss;
36 ss << std::hex;
37
38 for (int i = 0; i < 8; i++)
39 ss << dis(gen);
40 ss << "-";
41 for (int i = 0; i < 4; i++)
42 ss << dis(gen);
43 ss << "-4";
44 for (int i = 0; i < 3; i++)
45 ss << dis(gen);
46 ss << "-";
47 ss << dis2(gen);
48 for (int i = 0; i < 3; i++)
49 ss << dis(gen);
50 ss << "-";
51 for (int i = 0; i < 12; i++)
52 ss << dis(gen);
53
54 return ss.str();
55}
56
57std::string formatTime(std::chrono::system_clock::time_point tp)
58{
59 auto time = std::chrono::system_clock::to_time_t(tp);
60 char buffer[64];
61 std::tm tm{};
62 localtime_r(&time, &tm);
63 std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tm);
64 return buffer;
65}
66
67} // namespace
68
69// ==============================================================================
70// ScheduledTask Methods
71// ==============================================================================
72
73std::string ScheduledTask::getStateStr() const
74{
75 return taskStateName(state);
76}
77
79{
80 if (nextRunAt)
81 {
82 return formatTime(*nextRunAt);
83 }
84 return "Not scheduled";
85}
86
87// ==============================================================================
88// Helper Functions
89// ==============================================================================
90
91std::string taskPriorityName(TaskPriority priority)
92{
93 switch (priority)
94 {
96 return "Low";
98 return "Normal";
100 return "High";
102 return "Critical";
103 default:
104 return "Unknown";
105 }
106}
107
108std::string taskStateName(TaskState state)
109{
110 switch (state)
111 {
113 return "Pending";
115 return "Running";
117 return "Completed";
119 return "Failed";
121 return "Cancelled";
123 return "Paused";
124 default:
125 return "Unknown";
126 }
127}
128
129// ==============================================================================
130// Internal Task Entry
131// ==============================================================================
132
134{
136 std::function<TaskResult()> function;
137};
138
139// ==============================================================================
140// TaskScheduler Implementation
141// ==============================================================================
142
144{
145 std::map<std::string, InternalTask> tasks;
146 std::thread workerThread;
147 std::atomic<bool> running{false};
148 std::atomic<bool> paused{false};
149 std::atomic<bool> stopRequested{false};
150 std::condition_variable cv;
151 mutable std::mutex mutex;
152
153 // Callbacks
157
158 // Statistics
159 std::atomic<int> totalExecuted{0};
160 std::atomic<int> totalFailed{0};
161
162 void workerLoop();
163 void executeTask(const std::string& taskId);
164 std::optional<std::string> getNextTaskToRun();
165 void updateNextRunTime(const std::string& taskId);
166};
167
168TaskScheduler::TaskScheduler() : impl_(std::make_unique<Impl>()) {}
169
171{
172 stop(true);
173}
174
175// ==============================================================================
176// Lifecycle
177// ==============================================================================
178
180{
181 bool expected = false;
182 if (!impl_->running.compare_exchange_strong(expected, true))
183 {
184 return;
185 }
186
187 // Join any previous thread that has already exited
188 if (impl_->workerThread.joinable())
189 {
190 impl_->workerThread.join();
191 }
192
193 impl_->stopRequested = false;
194 impl_->workerThread = std::thread(&Impl::workerLoop, impl_.get());
195}
196
197void TaskScheduler::stop(bool waitForRunning)
198{
199 bool expected = true;
200 if (!impl_->running.compare_exchange_strong(expected, false))
201 {
202 return;
203 }
204
205 // Modify the predicate under the worker's mutex before notifying, even
206 // though stopRequested is atomic: otherwise a notify_all() that lands in
207 // the gap between the worker evaluating the predicate and enrolling in
208 // cv.wait_for() is lost, and the worker sleeps up to kMaxWait (1 hour) —
209 // making ~TaskScheduler()'s join() hang. (cppreference, condition_variable.)
210 {
211 std::lock_guard<std::mutex> lock(impl_->mutex);
212 impl_->stopRequested = true;
213 }
214 impl_->cv.notify_all();
215
216 if (waitForRunning && impl_->workerThread.joinable())
217 {
218 impl_->workerThread.join();
219 }
220}
221
223{
224 return impl_->running;
225}
226
228{
229 // Set under the mutex so the change is ordered against the worker's
230 // predicate evaluation (no notify needed — pausing doesn't wake anyone).
231 std::lock_guard<std::mutex> lock(impl_->mutex);
232 impl_->paused = true;
233}
234
236{
237 // Clear the predicate under the mutex before notifying, to avoid a lost
238 // wakeup (see stop() above).
239 {
240 std::lock_guard<std::mutex> lock(impl_->mutex);
241 impl_->paused = false;
242 }
243 impl_->cv.notify_all();
244}
245
247{
248 return impl_->paused;
249}
250
251// ==============================================================================
252// Task Scheduling
253// ==============================================================================
254
256{
257 std::lock_guard<std::mutex> lock(impl_->mutex);
258
259 InternalTask task;
260 task.info.id = generateUUID();
261 task.info.name = def.name;
262 task.info.description = def.description;
263 task.info.priority = def.priority;
265 task.info.createdAt = std::chrono::system_clock::now();
266 task.info.isRecurring = def.recurring;
267 task.info.interval = def.interval;
268 task.info.maxRuns = def.maxRuns;
269 task.info.runOnStartup = def.runOnStartup;
271 task.info.maxRetries = def.maxRetries;
272 task.function = def.task;
273
274 // Calculate scheduled time
275 if (def.runAt)
276 {
277 task.info.scheduledFor = *def.runAt;
278 task.info.nextRunAt = *def.runAt;
279 }
280 else if (def.delay)
281 {
282 task.info.scheduledFor = std::chrono::system_clock::now() + *def.delay;
283 task.info.nextRunAt = task.info.scheduledFor;
284 }
285 else if (def.runOnStartup)
286 {
287 task.info.scheduledFor = std::chrono::system_clock::now();
288 task.info.nextRunAt = task.info.scheduledFor;
289 }
290 else if (def.recurring && def.interval.count() > 0)
291 {
292 task.info.scheduledFor = std::chrono::system_clock::now() + def.interval;
293 task.info.nextRunAt = task.info.scheduledFor;
294 }
295 else
296 {
297 task.info.scheduledFor = std::chrono::system_clock::now();
298 task.info.nextRunAt = task.info.scheduledFor;
299 }
300
301 std::string taskId = task.info.id;
302 impl_->tasks[taskId] = std::move(task);
303
304 impl_->cv.notify_one();
305 return taskId;
306}
307
308std::string TaskScheduler::scheduleOnce(const std::string& name, std::chrono::seconds delay,
309 TaskFunction task, TaskPriority priority)
310{
311 TaskDefinition def;
312 def.name = name;
313 def.task = std::move(task);
314 def.priority = priority;
315 def.delay = delay;
316 return schedule(def);
317}
318
319std::string TaskScheduler::scheduleAt(const std::string& name,
320 std::chrono::system_clock::time_point when, TaskFunction task,
321 TaskPriority priority)
322{
323 TaskDefinition def;
324 def.name = name;
325 def.task = std::move(task);
326 def.priority = priority;
327 def.runAt = when;
328 return schedule(def);
329}
330
331std::string TaskScheduler::scheduleRecurring(const std::string& name, std::chrono::seconds interval,
332 TaskFunction task, TaskPriority priority,
333 bool runImmediately)
334{
335 TaskDefinition def;
336 def.name = name;
337 def.task = std::move(task);
338 def.priority = priority;
339 def.recurring = true;
340 def.interval = interval;
341 def.runOnStartup = runImmediately;
342 return schedule(def);
343}
344
345std::string TaskScheduler::runNow(const std::string& name, TaskFunction task, TaskPriority priority)
346{
347 return scheduleOnce(name, std::chrono::seconds(0), std::move(task), priority);
348}
349
350// ==============================================================================
351// Task Management
352// ==============================================================================
353
354std::optional<ScheduledTask> TaskScheduler::getTask(const std::string& taskId) const
355{
356 std::lock_guard<std::mutex> lock(impl_->mutex);
357
358 auto it = impl_->tasks.find(taskId);
359 if (it != impl_->tasks.end())
360 {
361 return it->second.info;
362 }
363 return std::nullopt;
364}
365
366std::optional<ScheduledTask> TaskScheduler::getTaskByName(const std::string& name) const
367{
368 std::lock_guard<std::mutex> lock(impl_->mutex);
369
370 for (const auto& [id, task] : impl_->tasks)
371 {
372 if (task.info.name == name)
373 {
374 return task.info;
375 }
376 }
377 return std::nullopt;
378}
379
380std::vector<ScheduledTask> TaskScheduler::getAllTasks() const
381{
382 std::lock_guard<std::mutex> lock(impl_->mutex);
383
384 std::vector<ScheduledTask> result;
385 for (const auto& [id, task] : impl_->tasks)
386 {
387 result.push_back(task.info);
388 }
389 return result;
390}
391
392std::vector<ScheduledTask> TaskScheduler::getTasksByState(TaskState state) const
393{
394 std::lock_guard<std::mutex> lock(impl_->mutex);
395
396 std::vector<ScheduledTask> result;
397 for (const auto& [id, task] : impl_->tasks)
398 {
399 if (task.info.state == state)
400 {
401 result.push_back(task.info);
402 }
403 }
404 return result;
405}
406
407std::vector<ScheduledTask> TaskScheduler::getPendingTasks() const
408{
410 std::sort(tasks.begin(), tasks.end(),
411 [](const auto& a, const auto& b)
412 {
413 if (!a.nextRunAt)
414 return false;
415 if (!b.nextRunAt)
416 return true;
417 return *a.nextRunAt < *b.nextRunAt;
418 });
419 return tasks;
420}
421
422bool TaskScheduler::cancelTask(const std::string& taskId)
423{
424 OnTaskStateChange callbackCopy;
425 bool cancelled = false;
426
427 {
428 std::lock_guard<std::mutex> lock(impl_->mutex);
429
430 auto it = impl_->tasks.find(taskId);
431 if (it != impl_->tasks.end())
432 {
433 if (it->second.info.state == TaskState::Pending ||
434 it->second.info.state == TaskState::Paused)
435 {
436 it->second.info.state = TaskState::Cancelled;
437 callbackCopy = impl_->onTaskStateChange;
438 cancelled = true;
439 }
440 }
441 }
442
443 if (cancelled && callbackCopy)
444 {
445 callbackCopy(taskId, TaskState::Cancelled);
446 }
447
448 return cancelled;
449}
450
451int TaskScheduler::cancelTasksByName(const std::string& name)
452{
453 OnTaskStateChange callbackCopy;
454 std::vector<std::string> cancelledIds;
455
456 {
457 std::lock_guard<std::mutex> lock(impl_->mutex);
458
459 for (auto& [id, task] : impl_->tasks)
460 {
461 if (task.info.name == name &&
462 (task.info.state == TaskState::Pending || task.info.state == TaskState::Paused))
463 {
464 task.info.state = TaskState::Cancelled;
465 cancelledIds.push_back(id);
466 }
467 }
468 callbackCopy = impl_->onTaskStateChange;
469 }
470
471 if (callbackCopy)
472 {
473 for (const auto& id : cancelledIds)
474 {
475 callbackCopy(id, TaskState::Cancelled);
476 }
477 }
478
479 return static_cast<int>(cancelledIds.size());
480}
481
483{
484 OnTaskStateChange callbackCopy;
485 std::vector<std::string> cancelledIds;
486
487 {
488 std::lock_guard<std::mutex> lock(impl_->mutex);
489
490 for (auto& [id, task] : impl_->tasks)
491 {
492 if (task.info.state == TaskState::Pending)
493 {
494 task.info.state = TaskState::Cancelled;
495 cancelledIds.push_back(id);
496 }
497 }
498 callbackCopy = impl_->onTaskStateChange;
499 }
500
501 if (callbackCopy)
502 {
503 for (const auto& id : cancelledIds)
504 {
505 callbackCopy(id, TaskState::Cancelled);
506 }
507 }
508
509 return static_cast<int>(cancelledIds.size());
510}
511
512bool TaskScheduler::pauseTask(const std::string& taskId)
513{
514 OnTaskStateChange callbackCopy;
515 bool paused = false;
516
517 {
518 std::lock_guard<std::mutex> lock(impl_->mutex);
519
520 auto it = impl_->tasks.find(taskId);
521 if (it != impl_->tasks.end() && it->second.info.state == TaskState::Pending)
522 {
523 it->second.info.state = TaskState::Paused;
524 callbackCopy = impl_->onTaskStateChange;
525 paused = true;
526 }
527 }
528
529 if (paused && callbackCopy)
530 {
531 callbackCopy(taskId, TaskState::Paused);
532 }
533
534 return paused;
535}
536
537bool TaskScheduler::resumeTask(const std::string& taskId)
538{
539 OnTaskStateChange callbackCopy;
540 bool resumed = false;
541
542 {
543 std::lock_guard<std::mutex> lock(impl_->mutex);
544
545 auto it = impl_->tasks.find(taskId);
546 if (it != impl_->tasks.end() && it->second.info.state == TaskState::Paused)
547 {
548 it->second.info.state = TaskState::Pending;
549 callbackCopy = impl_->onTaskStateChange;
550 resumed = true;
551 }
552
553 if (resumed)
554 {
555 impl_->cv.notify_one();
556 }
557 }
558
559 if (resumed && callbackCopy)
560 {
561 callbackCopy(taskId, TaskState::Pending);
562 }
563
564 return resumed;
565}
566
567bool TaskScheduler::rescheduleTask(const std::string& taskId,
568 std::chrono::system_clock::time_point newTime)
569{
570 std::lock_guard<std::mutex> lock(impl_->mutex);
571
572 auto it = impl_->tasks.find(taskId);
573 if (it != impl_->tasks.end())
574 {
575 it->second.info.scheduledFor = newTime;
576 it->second.info.nextRunAt = newTime;
577
578 if (it->second.info.state == TaskState::Completed ||
579 it->second.info.state == TaskState::Failed)
580 {
581 it->second.info.state = TaskState::Pending;
582 }
583
584 impl_->cv.notify_one();
585 return true;
586 }
587 return false;
588}
589
590bool TaskScheduler::setTaskInterval(const std::string& taskId, std::chrono::seconds newInterval)
591{
592 std::lock_guard<std::mutex> lock(impl_->mutex);
593
594 auto it = impl_->tasks.find(taskId);
595 if (it != impl_->tasks.end() && it->second.info.isRecurring)
596 {
597 it->second.info.interval = newInterval;
598 return true;
599 }
600 return false;
601}
602
603bool TaskScheduler::triggerNow(const std::string& taskId)
604{
605 std::lock_guard<std::mutex> lock(impl_->mutex);
606
607 auto it = impl_->tasks.find(taskId);
608 if (it != impl_->tasks.end())
609 {
610 it->second.info.nextRunAt = std::chrono::system_clock::now();
611 it->second.info.state = TaskState::Pending;
612
613 impl_->cv.notify_one();
614 return true;
615 }
616 return false;
617}
618
620{
621 std::lock_guard<std::mutex> lock(impl_->mutex);
622
623 int count = 0;
624 for (auto it = impl_->tasks.begin(); it != impl_->tasks.end();)
625 {
626 if (it->second.info.state == TaskState::Completed ||
627 it->second.info.state == TaskState::Cancelled ||
628 (it->second.info.state == TaskState::Failed && !it->second.info.isRecurring))
629 {
630 it = impl_->tasks.erase(it);
631 count++;
632 }
633 else
634 {
635 ++it;
636 }
637 }
638 return count;
639}
640
641// ==============================================================================
642// Built-in Tasks
643// ==============================================================================
644
646 std::chrono::hours interval)
647{
648 TaskDefinition def;
649 def.name = "update-check";
650 def.description = "Check for game updates across stores";
651 def.task = std::move(checkFunction);
653 def.recurring = true;
654 def.interval = std::chrono::duration_cast<std::chrono::seconds>(interval);
655 def.runOnStartup = true;
656 return schedule(def);
657}
658
660 std::chrono::minutes interval)
661{
662 TaskDefinition def;
663 def.name = "cloud-sync";
664 def.description = "Synchronize cloud saves";
665 def.task = std::move(syncFunction);
667 def.recurring = true;
668 def.interval = std::chrono::duration_cast<std::chrono::seconds>(interval);
669 return schedule(def);
670}
671
673 std::chrono::hours interval)
674{
675 TaskDefinition def;
676 def.name = "cache-cleanup";
677 def.description = "Clean up old cache files";
678 def.task = std::move(cleanupFunction);
680 def.recurring = true;
681 def.interval = std::chrono::duration_cast<std::chrono::seconds>(interval);
682 return schedule(def);
683}
684
686 std::chrono::hours interval)
687{
688 TaskDefinition def;
689 def.name = "log-cleanup";
690 def.description = "Clean up old log files";
691 def.task = std::move(cleanupFunction);
693 def.recurring = true;
694 def.interval = std::chrono::duration_cast<std::chrono::seconds>(interval);
695 return schedule(def);
696}
697
698// ==============================================================================
699// Statistics
700// ==============================================================================
701
703{
704 std::lock_guard<std::mutex> lock(impl_->mutex);
705 return static_cast<int>(impl_->tasks.size());
706}
707
709{
710 return static_cast<int>(getTasksByState(TaskState::Pending).size());
711}
712
714{
715 return static_cast<int>(getTasksByState(TaskState::Running).size());
716}
717
719{
720 return impl_->totalExecuted;
721}
722
724{
725 return impl_->totalFailed;
726}
727
728// ==============================================================================
729// Event Subscriptions
730// ==============================================================================
731
733{
734 std::lock_guard<std::mutex> lock(impl_->mutex);
735 impl_->onTaskComplete = std::move(callback);
736}
737
739{
740 std::lock_guard<std::mutex> lock(impl_->mutex);
741 impl_->onTaskError = std::move(callback);
742}
743
745{
746 std::lock_guard<std::mutex> lock(impl_->mutex);
747 impl_->onTaskStateChange = std::move(callback);
748}
749
750// ==============================================================================
751// Persistence
752// ==============================================================================
753
754bool TaskScheduler::saveTasks(const std::string& path) const
755{
756 std::lock_guard<std::mutex> lock(impl_->mutex);
757
758 std::ofstream file(path);
759 if (!file)
760 {
761 return false;
762 }
763
764 // Simple format - in production, use JSON
765 for (const auto& [id, task] : impl_->tasks)
766 {
767 if (task.info.isRecurring && task.info.enabled)
768 {
769 file << task.info.name << "|" << task.info.interval.count() << "|"
770 << static_cast<int>(task.info.priority) << "\n";
771 }
772 }
773
774 return true;
775}
776
777bool TaskScheduler::loadTasks(const std::string& /*path*/)
778{
779 // Tasks need their functions, so we can't fully restore from disk
780 // This would typically be used to restore configuration,
781 // and the application would need to re-register the task functions
782 return true;
783}
784
785// ==============================================================================
786// Private Methods
787// ==============================================================================
788
790{
791 while (!stopRequested)
792 {
793 std::unique_lock<std::mutex> lock(mutex);
794
795 // Find next task to run
796 auto nextTaskId = getNextTaskToRun();
797
798 if (!nextTaskId || paused)
799 {
800 // Wait for a signal or timeout. No predicate needed here because the
801 // loop re-checks stopRequested, paused, and getNextTaskToRun() on each
802 // iteration, so spurious wakeups are handled correctly by the continue.
803 cv.wait_for(lock, std::chrono::seconds(1));
804 continue;
805 }
806
807 auto it = tasks.find(*nextTaskId);
808 if (it == tasks.end())
809 {
810 continue;
811 }
812
813 auto& task = it->second;
814 auto now = std::chrono::system_clock::now();
815
816 // Check if it's time to run
817 if (!task.info.nextRunAt || *task.info.nextRunAt > now)
818 {
819 // Wait until task is due. Cap the wait at 1 hour as defence-in-
820 // depth: every code path that adds, cancels, or expedites a
821 // task already calls cv.notify_*, so in practice this cap is
822 // never reached. But a future change that forgets to notify
823 // would otherwise leave the worker silent for whatever
824 // `nextRunAt` says — even days, if the user scheduled a
825 // recurring task at a long interval. Capping limits worst-case
826 // latency to one wakeup per hour.
827 constexpr auto kMaxWait = std::chrono::hours(1);
828 auto waitTime = task.info.nextRunAt
829 ? std::chrono::duration_cast<std::chrono::milliseconds>(
830 *task.info.nextRunAt - now)
831 : std::chrono::milliseconds(1000);
832 if (waitTime > kMaxWait)
833 {
834 waitTime = std::chrono::duration_cast<std::chrono::milliseconds>(kMaxWait);
835 }
836
837 if (waitTime.count() > 0)
838 {
839 cv.wait_for(lock, waitTime);
840 }
841 continue;
842 }
843
844 // Execute the task. Bind a const reference to the optional's
845 // contained string; nextTaskId stays alive for the rest of this
846 // scope so the reference is valid through executeTask().
847 const std::string& taskId = *nextTaskId;
848 lock.unlock();
849
850 executeTask(taskId);
851 }
852
853 running = false;
854}
855
856void TaskScheduler::Impl::executeTask(const std::string& taskId)
857{
858 std::function<TaskResult()> taskFunc;
859 bool isRecurring = false;
860 OnTaskStateChange stateChangeCopy;
861
862 {
863 std::lock_guard<std::mutex> lock(mutex);
864 auto it = tasks.find(taskId);
865 if (it == tasks.end() || !it->second.function)
866 {
867 return;
868 }
869
870 auto& task = it->second;
871 if (task.info.state != TaskState::Pending)
872 {
873 return;
874 }
875
876 task.info.state = TaskState::Running;
877 taskFunc = task.function;
878 isRecurring = task.info.isRecurring;
879
880 stateChangeCopy = onTaskStateChange;
881 }
882
883 if (stateChangeCopy)
884 {
885 stateChangeCopy(taskId, TaskState::Running);
886 }
887
888 // Execute outside the lock
889 auto startTime = std::chrono::steady_clock::now();
890 TaskResult result;
891
892 try
893 {
894 result = taskFunc();
895 }
896 catch (const std::exception& e)
897 {
898 result.success = false;
899 result.message = "Exception: " + std::string(e.what());
900 result.errorDetails = e.what();
901 }
902 catch (...)
903 {
904 result.success = false;
905 result.message = "Unknown exception";
906 }
907
908 auto endTime = std::chrono::steady_clock::now();
909 result.duration = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
910
911 // Update task state and copy callbacks under lock
912 OnTaskComplete completeCopy;
913 OnTaskError errorCopy;
914 TaskState finalState = TaskState::Failed;
915 std::string errorMessage;
916 bool taskFound = false;
917
918 {
919 std::lock_guard<std::mutex> lock(mutex);
920 auto it = tasks.find(taskId);
921 if (it != tasks.end())
922 {
923 taskFound = true;
924 auto& task = it->second;
925 task.info.lastResult = result;
926 task.info.lastRunAt = std::chrono::system_clock::now();
927 task.info.runCount++;
928
929 if (result.success)
930 {
932
933 if (isRecurring &&
934 (task.info.maxRuns == 0 || task.info.runCount < task.info.maxRuns))
935 {
936 // Schedule next run
937 task.info.state = TaskState::Pending;
938 task.info.nextRunAt = std::chrono::system_clock::now() + task.info.interval;
939 task.info.failureCount = 0;
940 }
941 else
942 {
943 task.info.state = TaskState::Completed;
944 }
945
946 completeCopy = onTaskComplete;
947 }
948 else
949 {
950 totalFailed++;
951 task.info.failureCount++;
952
953 if (task.info.failureCount <= task.info.maxRetries)
954 {
955 // Retry with capped exponential backoff (max 1 hour)
956 int backoffSecs = 60 * std::min(task.info.failureCount, 60);
957 task.info.state = TaskState::Pending;
958 task.info.nextRunAt =
959 std::chrono::system_clock::now() + std::chrono::seconds(backoffSecs);
960 }
961 else if (isRecurring)
962 {
963 // Continue recurring despite failure; reset failure count so
964 // retries work properly on the next execution cycle
965 task.info.state = TaskState::Pending;
966 task.info.nextRunAt = std::chrono::system_clock::now() + task.info.interval;
967 task.info.failureCount = 0;
968 }
969 else
970 {
971 task.info.state = TaskState::Failed;
972 }
973
974 errorCopy = onTaskError;
975 errorMessage = result.message;
976 }
977
978 finalState = task.info.state;
979 stateChangeCopy = onTaskStateChange;
980 }
981 }
982
983 // Invoke callbacks outside the lock
984 if (taskFound)
985 {
986 if (result.success && completeCopy)
987 {
988 completeCopy(taskId, result);
989 }
990 else if (!result.success && errorCopy)
991 {
992 errorCopy(taskId, errorMessage);
993 }
994
995 if (stateChangeCopy)
996 {
997 stateChangeCopy(taskId, finalState);
998 }
999 }
1000}
1001
1002std::optional<std::string> TaskScheduler::Impl::getNextTaskToRun()
1003{
1004 // Find the pending task with earliest next run time and highest priority
1005 std::optional<std::string> bestTask;
1006 std::optional<std::chrono::system_clock::time_point> earliestTime;
1007 TaskPriority highestPriority = TaskPriority::Low;
1008
1009 for (const auto& [id, task] : tasks)
1010 {
1011 if (task.info.state != TaskState::Pending || !task.info.enabled)
1012 {
1013 continue;
1014 }
1015
1016 if (!task.info.nextRunAt)
1017 {
1018 continue;
1019 }
1020
1021 bool isBetter = false;
1022
1023 if (!bestTask)
1024 {
1025 isBetter = true;
1026 }
1027 else if (task.info.priority > highestPriority)
1028 {
1029 // Higher priority wins
1030 isBetter = true;
1031 }
1032 else if (task.info.priority == highestPriority && earliestTime &&
1033 *task.info.nextRunAt < *earliestTime)
1034 {
1035 // Same priority, earlier time wins
1036 isBetter = true;
1037 }
1038
1039 if (isBetter)
1040 {
1041 bestTask = id;
1042 earliestTime = task.info.nextRunAt;
1043 highestPriority = task.info.priority;
1044 }
1045 }
1046
1047 return bestTask;
1048}
1049
1050void TaskScheduler::Impl::updateNextRunTime(const std::string& taskId)
1051{
1052 auto it = tasks.find(taskId);
1053 if (it != tasks.end() && it->second.info.isRecurring)
1054 {
1055 it->second.info.nextRunAt = std::chrono::system_clock::now() + it->second.info.interval;
1056 }
1057}
std::optional< ScheduledTask > getTask(const std::string &taskId) const
Get a task by ID.
std::function< void(const std::string &taskId, const std::string &error)> OnTaskError
std::vector< ScheduledTask > getTasksByState(TaskState state) const
Get tasks by state.
int getTotalFailedCount() const
Get total failed tasks since start.
int pruneFinishedTasks()
Remove completed/cancelled/failed tasks from the list.
std::function< void(const std::string &taskId, TaskState newState)> OnTaskStateChange
bool isRunning() const
Check if the scheduler is running.
bool setTaskInterval(const std::string &taskId, std::chrono::seconds newInterval)
Change the interval of a recurring task.
std::string scheduleOnce(const std::string &name, std::chrono::seconds delay, TaskFunction task, TaskPriority priority=TaskPriority::Normal)
Schedule a one-shot task with a delay.
bool triggerNow(const std::string &taskId)
Trigger immediate execution of a task.
std::string addUpdateCheckTask(TaskFunction checkFunction, std::chrono::hours interval=std::chrono::hours(1))
Add an update check task.
void setOnTaskComplete(OnTaskComplete callback)
int getPendingTaskCount() const
Get number of pending tasks.
int getRunningTaskCount() const
Get number of running tasks.
bool loadTasks(const std::string &path)
Load scheduled tasks from disk.
int cancelTasksByName(const std::string &name)
Cancel all tasks with a given name.
void setOnTaskError(OnTaskError callback)
std::string scheduleRecurring(const std::string &name, std::chrono::seconds interval, TaskFunction task, TaskPriority priority=TaskPriority::Normal, bool runImmediately=false)
Schedule a recurring task.
std::string schedule(const TaskDefinition &def)
Schedule a task using a definition.
int cancelAllPendingTasks()
Cancel all pending tasks.
std::string runNow(const std::string &name, TaskFunction task, TaskPriority priority=TaskPriority::Critical)
Schedule a task to run immediately.
bool resumeTask(const std::string &taskId)
Resume a paused task.
void start()
Start the scheduler.
std::string addCacheCleanupTask(TaskFunction cleanupFunction, std::chrono::hours interval=std::chrono::hours(24))
Add a cache cleanup task.
bool isPaused() const
Check if paused.
std::optional< ScheduledTask > getTaskByName(const std::string &name) const
Get a task by name.
std::vector< ScheduledTask > getAllTasks() const
Get all scheduled tasks.
bool cancelTask(const std::string &taskId)
Cancel a task.
std::vector< ScheduledTask > getPendingTasks() const
Get pending tasks (sorted by next run time).
std::function< TaskResult()> TaskFunction
bool pauseTask(const std::string &taskId)
Pause a recurring task.
std::string scheduleAt(const std::string &name, std::chrono::system_clock::time_point when, TaskFunction task, TaskPriority priority=TaskPriority::Normal)
Schedule a task for a specific time.
int getTaskCount() const
Get number of scheduled tasks.
void setOnTaskStateChange(OnTaskStateChange callback)
std::string addLogCleanupTask(TaskFunction cleanupFunction, std::chrono::hours interval=std::chrono::hours(168))
Add a log cleanup task.
void resume()
Resume task execution.
void stop(bool waitForRunning=true)
Stop the scheduler.
int getTotalExecutedCount() const
Get total tasks executed since start.
bool rescheduleTask(const std::string &taskId, std::chrono::system_clock::time_point newTime)
Reschedule a task.
void pause()
Pause task execution.
bool saveTasks(const std::string &path) const
Save scheduled tasks to disk.
std::function< void(const std::string &taskId, const TaskResult &)> OnTaskComplete
std::string addCloudSyncTask(TaskFunction syncFunction, std::chrono::minutes interval=std::chrono::minutes(30))
Add a cloud sync task.
std::string formatTime(std::chrono::system_clock::time_point tp)
static std::string generateUUID()
ScheduledTask info
std::function< TaskResult()> function
Information about a scheduled task.
std::string name
Human-readable name.
std::chrono::system_clock::time_point createdAt
TaskPriority priority
std::string id
Unique task ID.
std::chrono::system_clock::time_point scheduledFor
TaskState state
int maxRuns
0 = unlimited
std::string getNextRunStr() const
std::string description
Task description.
std::chrono::seconds interval
std::string getStateStr() const
std::optional< std::chrono::system_clock::time_point > nextRunAt
bool runMissedOnStartup
Run if scheduled time was missed.
Definition for creating a new task.
std::string description
std::string name
std::optional< std::chrono::seconds > delay
TaskPriority priority
std::chrono::seconds interval
std::optional< std::chrono::system_clock::time_point > runAt
std::function< TaskResult()> task
Task function to execute.
Result of a task execution.
std::chrono::milliseconds duration
std::string message
std::optional< std::string > errorDetails
std::atomic< int > totalFailed
void updateNextRunTime(const std::string &taskId)
std::map< std::string, InternalTask > tasks
std::optional< std::string > getNextTaskToRun()
void executeTask(const std::string &taskId)
std::atomic< bool > stopRequested
std::atomic< int > totalExecuted
OnTaskComplete onTaskComplete
std::atomic< bool > running
std::atomic< bool > paused
OnTaskStateChange onTaskStateChange
std::condition_variable cv
std::string taskPriorityName(TaskPriority priority)
Get human-readable priority name.
std::string taskStateName(TaskState state)
Get human-readable state name.
TaskState
Current state of a scheduled task.
@ Completed
Finished successfully.
@ Pending
Waiting to run.
@ Running
Currently executing.
@ Cancelled
Was cancelled.
@ Failed
Finished with error.
@ Paused
Temporarily paused.
std::string taskStateName(TaskState state)
Get human-readable state name.
TaskPriority
Priority levels for tasks.
@ Critical
Must run ASAP (user-initiated).
@ Low
Background maintenance tasks.
@ High
Important tasks (update checks).
@ Normal
Regular scheduled tasks.