game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
task_scheduler.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// task_scheduler.h
4// ==============================================================================
5// Background task scheduling system
6// ==============================================================================
7// Provides functionality for scheduling and running background tasks:
8// - One-shot delayed tasks
9// - Recurring interval tasks
10// - Cron-like scheduled tasks
11// - Task prioritization and cancellation
12// - Error handling and retry logic
13//
14// ## About the Task Scheduler
15// Many launcher features need to run periodically in the background:
16// - Update checks for games across stores
17// - Cloud save synchronization
18// - Cache cleanup and maintenance
19// - System health monitoring
20//
21// ## Thread Safety
22// All public methods are thread-safe.
23// ==============================================================================
24
25#pragma once
26
27#include <chrono>
28#include <functional>
29#include <memory>
30#include <optional>
31#include <string>
32#include <vector>
33
34// ==============================================================================
35// Data Structures
36// ==============================================================================
37
38/**
39 * @enum TaskPriority
40 * @brief Priority levels for tasks
41 */
42enum class TaskPriority
43{
44 Low, ///< Background maintenance tasks
45 Normal, ///< Regular scheduled tasks
46 High, ///< Important tasks (update checks)
47 Critical ///< Must run ASAP (user-initiated)
48};
49
50/**
51 * @enum TaskState
52 * @brief Current state of a scheduled task
53 */
54enum class TaskState
55{
56 Pending, ///< Waiting to run
57 Running, ///< Currently executing
58 Completed, ///< Finished successfully
59 Failed, ///< Finished with error
60 Cancelled, ///< Was cancelled
61 Paused ///< Temporarily paused
62};
63
64/**
65 * @struct TaskResult
66 * @brief Result of a task execution
67 */
69{
70 bool success = true;
71 std::string message;
72 std::chrono::milliseconds duration{0};
73 std::optional<std::string> errorDetails;
74};
75
76/**
77 * @struct ScheduledTask
78 * @brief Information about a scheduled task
79 */
81{
82 std::string id; ///< Unique task ID
83 std::string name; ///< Human-readable name
84 std::string description; ///< Task description
87
88 // Timing
89 std::chrono::system_clock::time_point createdAt;
90 std::chrono::system_clock::time_point scheduledFor;
91 std::optional<std::chrono::system_clock::time_point> lastRunAt;
92 std::optional<std::chrono::system_clock::time_point> nextRunAt;
93
94 // Recurrence
95 bool isRecurring = false;
96 std::chrono::seconds interval{0};
97 int runCount = 0;
98 int maxRuns = 0; ///< 0 = unlimited
99
100 // Execution info
101 std::optional<TaskResult> lastResult;
103 int maxRetries = 3;
104
105 // Settings
106 bool runOnStartup = false;
107 bool runMissedOnStartup = true; ///< Run if scheduled time was missed
108 bool enabled = true;
109
110 std::string getStateStr() const;
111 std::string getNextRunStr() const;
112};
113
114/**
115 * @struct TaskDefinition
116 * @brief Definition for creating a new task
117 */
119{
120 std::string name;
121 std::string description;
122 std::function<TaskResult()> task; ///< Task function to execute
124
125 // One-shot scheduling
126 std::optional<std::chrono::system_clock::time_point> runAt;
127 std::optional<std::chrono::seconds> delay;
128
129 // Recurring scheduling
130 bool recurring = false;
131 std::chrono::seconds interval{0};
132 int maxRuns = 0;
133
134 // Options
135 bool runOnStartup = false;
137 int maxRetries = 3;
138 std::chrono::seconds retryDelay{60};
139};
140
141// ==============================================================================
142// TaskScheduler Class
143// ==============================================================================
144
145/**
146 * @class TaskScheduler
147 * @brief Service for scheduling and running background tasks
148 *
149 * Provides a flexible system for scheduling tasks to run at specific times
150 * or at regular intervals.
151 *
152 * ## Usage Example
153 * @code
154 * TaskScheduler scheduler;
155 * scheduler.start();
156 *
157 * // Schedule a one-shot task
158 * scheduler.scheduleOnce("check-updates",
159 * std::chrono::minutes(5),
160 * []() { return checkForUpdates(); });
161 *
162 * // Schedule a recurring task
163 * scheduler.scheduleRecurring("cloud-sync",
164 * std::chrono::hours(1),
165 * []() { return syncCloudSaves(); });
166 *
167 * // Stop the scheduler
168 * scheduler.stop();
169 * @endcode
170 */
172{
173 public:
174 using TaskFunction = std::function<TaskResult()>;
175 using OnTaskComplete = std::function<void(const std::string& taskId, const TaskResult&)>;
176 using OnTaskError = std::function<void(const std::string& taskId, const std::string& error)>;
177 using OnTaskStateChange = std::function<void(const std::string& taskId, TaskState newState)>;
178
181
182 // Non-copyable
183 TaskScheduler(const TaskScheduler&) = delete;
185
186 // ==========================================================================
187 // Lifecycle
188 // ==========================================================================
189
190 /**
191 * @brief Start the scheduler
192 *
193 * Begins processing scheduled tasks. Must be called before tasks will run.
194 */
195 void start();
196
197 /**
198 * @brief Stop the scheduler
199 * @param waitForRunning Wait for currently running tasks to complete
200 */
201 void stop(bool waitForRunning = true);
202
203 /**
204 * @brief Check if the scheduler is running
205 */
206 bool isRunning() const;
207
208 /**
209 * @brief Pause task execution
210 */
211 void pause();
212
213 /**
214 * @brief Resume task execution
215 */
216 void resume();
217
218 /**
219 * @brief Check if paused
220 */
221 bool isPaused() const;
222
223 // ==========================================================================
224 // Task Scheduling
225 // ==========================================================================
226
227 /**
228 * @brief Schedule a task using a definition
229 * @param def Task definition
230 * @return Task ID
231 */
232 std::string schedule(const TaskDefinition& def);
233
234 /**
235 * @brief Schedule a one-shot task with a delay
236 * @param name Task name
237 * @param delay Delay before running
238 * @param task Task function
239 * @param priority Task priority
240 * @return Task ID
241 */
242 std::string scheduleOnce(const std::string& name, std::chrono::seconds delay, TaskFunction task,
244
245 /**
246 * @brief Schedule a task for a specific time
247 * @param name Task name
248 * @param when Time to run
249 * @param task Task function
250 * @param priority Task priority
251 * @return Task ID
252 */
253 std::string scheduleAt(const std::string& name, std::chrono::system_clock::time_point when,
255
256 /**
257 * @brief Schedule a recurring task
258 * @param name Task name
259 * @param interval Time between runs
260 * @param task Task function
261 * @param priority Task priority
262 * @param runImmediately Run once immediately
263 * @return Task ID
264 */
265 std::string scheduleRecurring(const std::string& name, std::chrono::seconds interval,
267 bool runImmediately = false);
268
269 /**
270 * @brief Schedule a task to run immediately
271 * @param name Task name
272 * @param task Task function
273 * @param priority Task priority
274 * @return Task ID
275 */
276 std::string runNow(const std::string& name, TaskFunction task,
278
279 // ==========================================================================
280 // Task Management
281 // ==========================================================================
282
283 /**
284 * @brief Get a task by ID
285 * @param taskId Task ID
286 * @return Task info if found
287 */
288 std::optional<ScheduledTask> getTask(const std::string& taskId) const;
289
290 /**
291 * @brief Get a task by name
292 * @param name Task name
293 * @return Task info if found
294 */
295 std::optional<ScheduledTask> getTaskByName(const std::string& name) const;
296
297 /**
298 * @brief Get all scheduled tasks
299 * @return Vector of tasks
300 */
301 std::vector<ScheduledTask> getAllTasks() const;
302
303 /**
304 * @brief Get tasks by state
305 * @param state Task state to filter
306 * @return Vector of matching tasks
307 */
308 std::vector<ScheduledTask> getTasksByState(TaskState state) const;
309
310 /**
311 * @brief Get pending tasks (sorted by next run time)
312 * @return Vector of pending tasks
313 */
314 std::vector<ScheduledTask> getPendingTasks() const;
315
316 /**
317 * @brief Cancel a task
318 * @param taskId Task ID
319 * @return True if cancelled
320 */
321 bool cancelTask(const std::string& taskId);
322
323 /**
324 * @brief Cancel all tasks with a given name
325 * @param name Task name
326 * @return Number of tasks cancelled
327 */
328 int cancelTasksByName(const std::string& name);
329
330 /**
331 * @brief Cancel all pending tasks
332 * @return Number of tasks cancelled
333 */
335
336 /**
337 * @brief Pause a recurring task
338 * @param taskId Task ID
339 * @return True if paused
340 */
341 bool pauseTask(const std::string& taskId);
342
343 /**
344 * @brief Resume a paused task
345 * @param taskId Task ID
346 * @return True if resumed
347 */
348 bool resumeTask(const std::string& taskId);
349
350 /**
351 * @brief Reschedule a task
352 * @param taskId Task ID
353 * @param newTime New scheduled time
354 * @return True if rescheduled
355 */
356 bool rescheduleTask(const std::string& taskId, std::chrono::system_clock::time_point newTime);
357
358 /**
359 * @brief Change the interval of a recurring task
360 * @param taskId Task ID
361 * @param newInterval New interval
362 * @return True if changed
363 */
364 bool setTaskInterval(const std::string& taskId, std::chrono::seconds newInterval);
365
366 /**
367 * @brief Trigger immediate execution of a task
368 * @param taskId Task ID
369 * @return True if triggered
370 */
371 bool triggerNow(const std::string& taskId);
372
373 /**
374 * @brief Remove completed/cancelled/failed tasks from the list
375 * @return Number of tasks removed
376 */
377 int pruneFinishedTasks();
378
379 // ==========================================================================
380 // Built-in Tasks (commonly needed)
381 // ==========================================================================
382
383 /**
384 * @brief Add an update check task
385 * @param checkFunction Function that checks for updates
386 * @param interval How often to check
387 * @return Task ID
388 */
389 std::string addUpdateCheckTask(TaskFunction checkFunction,
390 std::chrono::hours interval = std::chrono::hours(1));
391
392 /**
393 * @brief Add a cloud sync task
394 * @param syncFunction Function that syncs cloud saves
395 * @param interval How often to sync
396 * @return Task ID
397 */
398 std::string addCloudSyncTask(TaskFunction syncFunction,
399 std::chrono::minutes interval = std::chrono::minutes(30));
400
401 /**
402 * @brief Add a cache cleanup task
403 * @param cleanupFunction Function that cleans caches
404 * @param interval How often to clean
405 * @return Task ID
406 */
407 std::string addCacheCleanupTask(TaskFunction cleanupFunction,
408 std::chrono::hours interval = std::chrono::hours(24));
409
410 /**
411 * @brief Add a log cleanup task
412 * @param cleanupFunction Function that cleans logs
413 * @param interval How often to clean
414 * @return Task ID
415 */
416 std::string addLogCleanupTask(TaskFunction cleanupFunction,
417 std::chrono::hours interval = std::chrono::hours(168)); // Weekly
418
419 // ==========================================================================
420 // Statistics
421 // ==========================================================================
422
423 /**
424 * @brief Get number of scheduled tasks
425 */
426 int getTaskCount() const;
427
428 /**
429 * @brief Get number of pending tasks
430 */
431 int getPendingTaskCount() const;
432
433 /**
434 * @brief Get number of running tasks
435 */
436 int getRunningTaskCount() const;
437
438 /**
439 * @brief Get total tasks executed since start
440 */
441 int getTotalExecutedCount() const;
442
443 /**
444 * @brief Get total failed tasks since start
445 */
446 int getTotalFailedCount() const;
447
448 // ==========================================================================
449 // Event Subscriptions
450 // ==========================================================================
451
452 void setOnTaskComplete(OnTaskComplete callback);
453 void setOnTaskError(OnTaskError callback);
455
456 // ==========================================================================
457 // Persistence (optional)
458 // ==========================================================================
459
460 /**
461 * @brief Save scheduled tasks to disk
462 * @param path File path
463 * @return True on success
464 */
465 bool saveTasks(const std::string& path) const;
466
467 /**
468 * @brief Load scheduled tasks from disk
469 * @param path File path
470 * @return True on success
471 */
472 bool loadTasks(const std::string& path);
473
474 private:
475 struct Impl;
476 std::unique_ptr<Impl> impl_;
477};
478
479/**
480 * @brief Get human-readable priority name
481 */
482std::string taskPriorityName(TaskPriority priority);
483
484/**
485 * @brief Get human-readable state name
486 */
487std::string taskStateName(TaskState state);
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.
TaskScheduler(const TaskScheduler &)=delete
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)
TaskScheduler & operator=(const TaskScheduler &)=delete
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.
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
std::optional< std::chrono::system_clock::time_point > lastRunAt
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.
std::optional< TaskResult > lastResult
Definition for creating a new task.
std::chrono::seconds retryDelay
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::string taskPriorityName(TaskPriority priority)
Get human-readable priority 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.