PACS System 0.1.0
PACS DICOM system library
Loading...
Searching...
No Matches
task_scheduler.h
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2021-2025, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
18#pragma once
19
21
22#include <atomic>
23#include <chrono>
24#include <condition_variable>
25#include <functional>
26#include <map>
27#include <memory>
28#include <mutex>
29#include <optional>
30#include <queue>
31#include <string>
32#include <thread>
33#include <vector>
34
35// Forward declarations for kcenon ecosystem
36namespace kcenon::thread {
37class thread_pool;
38} // namespace kcenon::thread
39
41class IExecutor;
42} // namespace kcenon::common::interfaces
43
44// Forward declarations for PACS modules
45namespace kcenon::pacs::storage {
46class index_database;
47class file_storage;
48} // namespace kcenon::pacs::storage
49
50namespace kcenon::pacs::workflow {
51
52// Forward declare Result type (defined in integration or common)
53template <typename T>
54class Result;
55
163public:
164 // =========================================================================
165 // Construction
166 // =========================================================================
167
174 explicit task_scheduler(
175 storage::index_database& database,
176 const task_scheduler_config& config = {});
177
187 storage::index_database& database,
188 storage::file_storage& file_storage,
189 std::shared_ptr<kcenon::thread::thread_pool> thread_pool,
190 const task_scheduler_config& config = {});
191
207 storage::index_database& database,
208 storage::file_storage& file_storage,
209 std::shared_ptr<kcenon::common::interfaces::IExecutor> executor,
210 const task_scheduler_config& config = {});
211
216
220
224
225 // =========================================================================
226 // Lifecycle Management
227 // =========================================================================
228
235 void start();
236
245 void stop(bool wait_for_completion = true);
246
252 [[nodiscard]] auto is_running() const noexcept -> bool;
253
254 // =========================================================================
255 // Task Scheduling - Cleanup
256 // =========================================================================
257
267 auto schedule_cleanup(const cleanup_config& config) -> task_id;
268
269 // =========================================================================
270 // Task Scheduling - Archive
271 // =========================================================================
272
282 auto schedule_archive(const archive_config& config) -> task_id;
283
284 // =========================================================================
285 // Task Scheduling - Verification
286 // =========================================================================
287
298
299 // =========================================================================
300 // Task Scheduling - Custom
301 // =========================================================================
302
312 auto schedule(
313 const std::string& name,
314 const std::string& description,
315 std::chrono::seconds interval,
317
327 auto schedule(
328 const std::string& name,
329 const std::string& description,
330 const cron_schedule& cron_expr,
332
342 auto schedule_once(
343 const std::string& name,
344 const std::string& description,
345 std::chrono::system_clock::time_point execute_at,
347
354 auto schedule(scheduled_task task) -> task_id;
355
356 // =========================================================================
357 // Task Management
358 // =========================================================================
359
365 [[nodiscard]] auto list_tasks() const -> std::vector<scheduled_task>;
366
373 [[nodiscard]] auto list_tasks(task_type type) const
374 -> std::vector<scheduled_task>;
375
382 [[nodiscard]] auto list_tasks(task_state state) const
383 -> std::vector<scheduled_task>;
384
391 [[nodiscard]] auto get_task(const task_id& id) const
392 -> std::optional<scheduled_task>;
393
403 auto cancel_task(const task_id& id) -> bool;
404
414 auto pause_task(const task_id& id) -> bool;
415
422 auto resume_task(const task_id& id) -> bool;
423
432 auto trigger_task(const task_id& id) -> bool;
433
441 auto update_schedule(const task_id& id, const kcenon::pacs::workflow::schedule& new_schedule) -> bool;
442
443 // =========================================================================
444 // Execution History
445 // =========================================================================
446
454 [[nodiscard]] auto get_execution_history(
455 const task_id& id,
456 std::size_t limit = 100) const -> std::vector<task_execution_record>;
457
464 [[nodiscard]] auto get_recent_executions(std::size_t limit = 100) const
465 -> std::vector<task_execution_record>;
466
473 void clear_history(const task_id& id, std::size_t keep_last = 0);
474
475 // =========================================================================
476 // Statistics and Monitoring
477 // =========================================================================
478
484 [[nodiscard]] auto get_stats() const -> scheduler_stats;
485
491 [[nodiscard]] auto pending_count() const noexcept -> std::size_t;
492
498 [[nodiscard]] auto running_count() const noexcept -> std::size_t;
499
500 // =========================================================================
501 // Persistence
502 // =========================================================================
503
509 auto save_tasks() const -> bool;
510
516 auto load_tasks() -> std::size_t;
517
518 // =========================================================================
519 // Configuration
520 // =========================================================================
521
528 task_scheduler_config::task_complete_callback callback);
529
536 task_scheduler_config::task_error_callback callback);
537
538private:
539 // =========================================================================
540 // Internal Methods
541 // =========================================================================
542
546 void run_loop();
547
553 void execute_cycle();
554
562
570 [[nodiscard]] auto calculate_next_run(
571 const kcenon::pacs::workflow::schedule& sched,
572 std::chrono::system_clock::time_point from =
573 std::chrono::system_clock::now()) const
574 -> std::optional<std::chrono::system_clock::time_point>;
575
583 [[nodiscard]] auto calculate_next_cron_run(
584 const cron_schedule& cron,
585 std::chrono::system_clock::time_point from) const
586 -> std::optional<std::chrono::system_clock::time_point>;
587
593 [[nodiscard]] auto generate_task_id() const -> task_id;
594
600 [[nodiscard]] auto generate_execution_id() const -> std::string;
601
608 [[nodiscard]] auto create_cleanup_callback(const cleanup_config& config)
610
617 [[nodiscard]] auto create_archive_callback(const archive_config& config)
619
626 [[nodiscard]] auto create_verification_callback(const verification_config& config)
628
635 void record_execution(const task_id& task_id,
636 const task_execution_record& record);
637
643 void update_stats(const task_execution_record& record);
644
650 [[nodiscard]] auto serialize_tasks() const -> std::string;
651
658 auto deserialize_tasks(const std::string& json) -> std::size_t;
659
660 // =========================================================================
661 // Member Variables
662 // =========================================================================
663
665 storage::index_database& database_;
666
668 storage::file_storage* file_storage_{nullptr};
669
671 std::shared_ptr<kcenon::thread::thread_pool> thread_pool_;
672
674 std::shared_ptr<kcenon::common::interfaces::IExecutor> executor_;
675
678
680 std::thread scheduler_thread_;
681
683 mutable std::mutex mutex_;
684
686 std::condition_variable cv_;
687
689 std::atomic<bool> stop_requested_{false};
690
692 std::atomic<bool> running_{false};
693
695 std::map<task_id, scheduled_task> tasks_;
696
698 mutable std::mutex tasks_mutex_;
699
701 std::map<task_id, std::vector<task_execution_record>> execution_history_;
702
704 mutable std::mutex history_mutex_;
705
707 std::atomic<std::size_t> running_count_{0};
708
711
713 mutable std::mutex stats_mutex_;
714
716 std::chrono::steady_clock::time_point start_time_;
717
719 mutable std::atomic<uint64_t> next_task_id_{1};
720
722 mutable std::atomic<uint64_t> next_execution_id_{1};
723};
724
725} // namespace kcenon::pacs::workflow
std::atomic< uint64_t > next_task_id_
Next task ID counter.
storage::file_storage * file_storage_
Optional reference to file storage.
storage::index_database & database_
Reference to PACS index database.
void execute_cycle()
Execute a single scheduler cycle.
auto generate_execution_id() const -> std::string
Generate unique execution ID.
std::map< task_id, scheduled_task > tasks_
All scheduled tasks (id -> task)
void update_stats(const task_execution_record &record)
Update statistics after execution.
auto deserialize_tasks(const std::string &json) -> std::size_t
Deserialize tasks from JSON.
auto execute_task(scheduled_task &task) -> task_execution_record
Execute a single task.
task_scheduler(const task_scheduler &)=delete
Non-copyable.
std::condition_variable cv_
Condition variable for sleep/wake.
auto pause_task(const task_id &id) -> bool
Pause a scheduled task.
std::atomic< bool > running_
Flag indicating scheduler is running.
auto cancel_task(const task_id &id) -> bool
Cancel a scheduled task.
auto create_verification_callback(const verification_config &config) -> task_callback_with_result
Create verification task callback.
auto save_tasks() const -> bool
Save all tasks to persistence storage.
std::mutex mutex_
Mutex for thread synchronization.
std::mutex stats_mutex_
Mutex for statistics.
task_scheduler(storage::index_database &database, const task_scheduler_config &config={})
Construct task scheduler.
task_scheduler_config config_
Service configuration.
std::shared_ptr< kcenon::common::interfaces::IExecutor > executor_
IExecutor for task execution (recommended, Issue #487)
auto running_count() const noexcept -> std::size_t
Get number of running tasks.
auto calculate_next_cron_run(const cron_schedule &cron, std::chrono::system_clock::time_point from) const -> std::optional< std::chrono::system_clock::time_point >
Calculate next run time for cron schedule.
auto create_archive_callback(const archive_config &config) -> task_callback_with_result
Create archive task callback.
auto serialize_tasks() const -> std::string
Serialize tasks to JSON.
void set_task_complete_callback(task_scheduler_config::task_complete_callback callback)
Set the task complete callback.
task_scheduler & operator=(task_scheduler &&)=delete
void set_error_callback(task_scheduler_config::task_error_callback callback)
Set the error callback.
auto is_running() const noexcept -> bool
Check if the scheduler is running.
std::thread scheduler_thread_
Background scheduler thread.
auto update_schedule(const task_id &id, const kcenon::pacs::workflow::schedule &new_schedule) -> bool
Update task schedule.
std::mutex tasks_mutex_
Mutex for tasks map.
auto schedule_verification(const verification_config &config) -> task_id
Schedule verification task.
auto get_stats() const -> scheduler_stats
Get scheduler statistics.
auto list_tasks() const -> std::vector< scheduled_task >
List all scheduled tasks.
void clear_history(const task_id &id, std::size_t keep_last=0)
Clear execution history for a task.
~task_scheduler()
Destructor - ensures graceful shutdown.
auto get_execution_history(const task_id &id, std::size_t limit=100) const -> std::vector< task_execution_record >
Get execution history for a task.
task_scheduler(task_scheduler &&)=delete
Non-movable.
auto schedule_archive(const archive_config &config) -> task_id
Schedule archive task.
void run_loop()
Background thread main loop.
auto generate_task_id() const -> task_id
Generate unique task ID.
task_scheduler & operator=(const task_scheduler &)=delete
auto calculate_next_run(const kcenon::pacs::workflow::schedule &sched, std::chrono::system_clock::time_point from=std::chrono::system_clock::now()) const -> std::optional< std::chrono::system_clock::time_point >
Calculate next run time for a schedule.
void record_execution(const task_id &task_id, const task_execution_record &record)
Record task execution.
auto resume_task(const task_id &id) -> bool
Resume a paused task.
auto get_recent_executions(std::size_t limit=100) const -> std::vector< task_execution_record >
Get all recent executions.
auto load_tasks() -> std::size_t
Load tasks from persistence storage.
std::mutex history_mutex_
Mutex for execution history.
std::map< task_id, std::vector< task_execution_record > > execution_history_
Execution history (task_id -> records)
auto get_task(const task_id &id) const -> std::optional< scheduled_task >
Get a specific task by ID.
auto schedule_cleanup(const cleanup_config &config) -> task_id
Schedule cleanup task.
std::atomic< std::size_t > running_count_
Running task count.
auto pending_count() const noexcept -> std::size_t
Get number of pending tasks.
scheduler_stats stats_
Scheduler statistics.
std::atomic< uint64_t > next_execution_id_
Next execution ID counter.
auto schedule_once(const std::string &name, const std::string &description, std::chrono::system_clock::time_point execute_at, task_callback_with_result callback) -> task_id
Schedule a one-time task.
std::shared_ptr< kcenon::thread::thread_pool > thread_pool_
Thread pool for parallel task execution (legacy)
void stop(bool wait_for_completion=true)
Stop the scheduler service.
auto trigger_task(const task_id &id) -> bool
Trigger immediate execution of a task.
std::chrono::steady_clock::time_point start_time_
Start time for uptime calculation.
auto create_cleanup_callback(const cleanup_config &config) -> task_callback_with_result
Create cleanup task callback.
void start()
Start the scheduler service.
std::atomic< bool > stop_requested_
Flag to signal shutdown.
task_state
Task execution state.
std::function< std::optional< std::string >()> task_callback_with_result
Task callback with result details.
task_type
Task type enumeration.
std::string task_id
Unique task identifier.
std::variant< interval_schedule, cron_schedule, one_time_schedule > schedule
Combined schedule type.
Configuration for archive scheduling.
Configuration for cleanup scheduling.
Statistics for task scheduler operations.
Configuration for the task scheduler service.
Configuration for verification scheduling.
Configuration for task scheduler service.
std::string_view name