Task Scheduler
Public header: #include "brookesia/lib_utils/task_scheduler.hpp"
Overview
task_scheduler is a Boost.Asio–based scheduler supporting immediate, delayed, and periodic tasks, with grouped serial/parallel execution.
Features
One-shot, delayed, periodic, and batch scheduling
Task groups and serial execution control
Pause, resume, cancel, and wait for completion
Statistics and pre/post callbacks
API Reference
Header File
Classes
-
class TaskScheduler
Asynchronous task scheduler built on top of
boost::asio::io_context.The scheduler supports immediate, delayed, and periodic tasks, optional task grouping, serial execution within groups, suspension and resumption of timer-driven tasks, and task lifecycle statistics.
Public Types
-
enum class TaskType
Kind of scheduled task.
Values:
-
enumerator Immediate
Task scheduled with
post()ordispatch().
-
enumerator Delayed
One-shot timer task scheduled with
post_delayed().
-
enumerator Periodic
Repeating timer task scheduled with
post_periodic().
-
enumerator Immediate
-
enum class TaskState
Runtime state reported for a scheduled task.
Values:
-
enumerator Running
Task is active and eligible to execute.
-
enumerator Suspended
Task timer is suspended.
-
enumerator Canceled
Task was canceled before completion.
-
enumerator Finished
Task finished execution or is no longer tracked.
-
enumerator Running
-
using TaskId = uint64_t
Identifier type assigned to each scheduled task.
-
using OnceTask = std::function<void()>
Callable type for one-shot tasks.
-
using PeriodicTask = std::function<bool()>
Callable type for periodic tasks.
Returning
falsestops future executions.
-
using Group = std::string
Task group name type.
-
using Executor = boost::asio::io_context::executor_type
Executor type exposed by the underlying
boost::asio::io_context.
-
using PreExecuteCallback = std::function<void(const Group&, TaskId, TaskType)>
Callback invoked when a task is selected by io_context and about to execute.
Note
This callback is invoked after the task is selected by io_context and just before the actual task logic executes, guaranteeing that the task will execute (unless an exception occurs in the callback itself)
- Param group
Group name of the task
- Param task_id
ID of the task about to execute
- Param task_type
Type of the task
-
using PostExecuteCallback = std::function<void(const Group&, TaskId, TaskType, bool success)>
Callback invoked after a task completes execution.
Note
This callback is invoked after the task logic completes, regardless of success or failure, providing a hook for cleanup, logging, or statistics
- Param group
Group name of the completed task
- Param task_id
ID of the completed task
- Param task_type
Type of the task
- Param success
Whether the task executed successfully
Public Functions
-
TaskScheduler() = default
Construct an idle task scheduler.
-
~TaskScheduler()
Stop the scheduler and release its resources.
-
TaskScheduler(const TaskScheduler&) = delete
Copy construction is not supported.
-
TaskScheduler &operator=(const TaskScheduler&) = delete
Copy assignment is not supported.
-
TaskScheduler(TaskScheduler&&) = delete
Move construction is not supported.
-
TaskScheduler &operator=(TaskScheduler&&) = delete
Move assignment is not supported.
-
bool start(const StartConfig &config)
Start the scheduler with a custom worker configuration.
- Parameters
config – [in] Worker-thread and callback configuration.
- Returns
trueon success, orfalsewhen startup fails.
-
inline bool start()
Start the scheduler with the default configuration.
- Returns
trueon success, orfalsewhen startup fails.
-
void stop()
Stop the scheduler and cancel all pending tasks.
Running tasks are allowed to finish, worker threads are joined, and internal state is reset.
-
inline bool is_running() const
Check whether the scheduler is running.
- Returns
truewhen worker threads and theio_contextare active, orfalseotherwise.
-
bool configure_group(const Group &group, const GroupConfig &config)
Configure execution behavior for a task group.
- Parameters
group – [in] Group name.
config – [in] Group behavior configuration.
- Returns
trueif the group was configured successfully, orfalseotherwise.
-
bool dispatch(OnceTask task, TaskId *id = nullptr, const Group &group = "")
Dispatch a task for immediate execution when possible.
When called from a scheduler worker thread, the task may run inline instead of being enqueued.
- Parameters
task – [in] Task to execute.
id – [out] Optional pointer that receives the assigned task ID.
group – [in] Optional task group name.
- Returns
trueif the task was scheduled successfully, orfalseotherwise.
-
bool post(OnceTask task, TaskId *id = nullptr, const Group &group = "")
Post a task to the scheduler queue.
- Parameters
task – [in] Task to execute.
id – [out] Optional pointer that receives the assigned task ID.
group – [in] Optional task group name.
- Returns
trueif the task was scheduled successfully, orfalseotherwise.
-
bool post_delayed(OnceTask task, int delay_ms, TaskId *id = nullptr, const Group &group = "")
Schedule a one-shot task to run after a delay.
- Parameters
task – [in] Task to execute.
delay_ms – [in] Delay before execution, in milliseconds.
id – [out] Optional pointer that receives the assigned task ID.
group – [in] Optional task group name.
- Returns
trueif the task was scheduled successfully, orfalseotherwise.
-
bool post_periodic(PeriodicTask task, int interval_ms, TaskId *id = nullptr, const Group &group = "")
Schedule a periodic task.
The task will be executed repeatedly at the specified interval. Return false from the task to stop the periodic execution.
- Parameters
task – [in] Periodic task to execute. Returning
falsestops future runs.interval_ms – [in] Interval between executions, in milliseconds.
id – [out] Optional pointer that receives the assigned task ID.
group – [in] Optional task group name.
- Returns
trueif the task was scheduled successfully, orfalseotherwise.
-
bool post_batch(std::vector<OnceTask> tasks, std::vector<TaskId> *ids = nullptr, const Group &group = "")
Post multiple one-shot tasks as a batch.
- Parameters
tasks – [in] Vector of tasks to execute.
ids – [out] Optional pointer that receives the assigned task IDs.
group – [in] Optional task group name applied to every task.
- Returns
trueif all tasks were scheduled successfully, orfalseotherwise.
-
void cancel_group(const Group &group)
Cancel every task in a group.
- Parameters
group – [in] Group name.
-
void cancel_all()
Cancel all tracked tasks.
-
bool suspend(TaskId id)
Suspend a delayed or periodic task.
Only delayed and periodic tasks can be suspended.
- Parameters
id – [in] Task ID to suspend.
- Returns
trueif the task was suspended successfully, orfalseotherwise.
-
size_t suspend_group(const Group &group)
Suspend all suspendable tasks in a group.
- Parameters
group – [in] Group name.
- Returns
Number of tasks suspended.
-
size_t suspend_all()
Suspend all suspendable tasks.
- Returns
Number of tasks suspended.
-
bool resume(TaskId id)
Resume a suspended delayed or periodic task.
- Parameters
id – [in] Task ID to resume.
- Returns
trueif the task was resumed successfully, orfalseotherwise.
-
size_t resume_group(const Group &group)
Resume all suspended tasks in a group.
- Parameters
group – [in] Group name.
- Returns
Number of tasks resumed.
-
size_t resume_all()
Resume all suspended tasks.
- Returns
Number of tasks resumed.
-
bool wait(TaskId id, int timeout_ms = -1)
Wait for a task to complete.
- Parameters
id – [in] Task ID to wait for.
timeout_ms – [in] Timeout in milliseconds.
-1waits indefinitely.
- Returns
trueif the task completed within the timeout, orfalseotherwise.
-
bool wait_group(const Group &group, int timeout_ms = -1)
Wait for all tasks in a group to complete.
- Parameters
group – [in] Group name.
timeout_ms – [in] Timeout in milliseconds.
-1waits indefinitely.
- Returns
trueif all tasks in the group completed within the timeout, orfalseotherwise.
-
bool wait_all(int timeout_ms = -1)
Wait for all tasks to complete.
- Parameters
timeout_ms – [in] Timeout in milliseconds.
-1waits indefinitely.- Returns
trueif all tasks completed within the timeout, orfalseotherwise.
-
bool restart_timer(TaskId id)
Restart the timer for a delayed or periodic task.
This resets the timer countdown to its original interval. Useful for implementing debounce or watchdog-like behavior where you want to postpone execution.
- Parameters
id – [in] Task ID whose timer should restart.
- Returns
trueif the timer restarted successfully, orfalsewhen the task is missing, has the wrong type, or is not running.
-
TaskType get_type(TaskId id) const
Query the type of a task.
- Parameters
id – [in] Task ID.
- Returns
Task type for the ID, or
TaskType::Immediatewhen the task is unknown.
-
TaskState get_state(TaskId id) const
Query the state of a task.
- Parameters
id – [in] Task ID.
- Returns
Task state for the ID, or
TaskState::Finishedwhen the task is unknown.
-
Group get_group(TaskId id) const
Query the group of a task.
- Parameters
id – [in] Task ID.
- Returns
Group name, or an empty string when the task is unknown or ungrouped.
-
size_t get_group_task_count(const Group &group) const
Query the number of tracked tasks in a group.
- Parameters
group – [in] Group name.
- Returns
Number of tasks currently associated with the group.
-
std::vector<Group> get_active_groups() const
Get all groups that currently contain tasks.
- Returns
Vector of active group names.
-
Statistics get_statistics() const
Get execution statistics accumulated by the scheduler.
- Returns
Statisticsstructure with task counters.
-
inline std::shared_ptr<Executor> get_executor()
Get a shared executor handle for the underlying
io_context.- Returns
Shared pointer to the executor, or
nullptrwhen the scheduler is not running.
-
inline size_t get_worker_count() const
Get the number of worker threads.
- Returns
Number of worker threads currently owned by the scheduler.
-
void reset_statistics()
Reset all accumulated statistics counters to zero.
-
struct GroupConfig
Configuration for a task group.
Public Members
-
bool enable_serial_execution = false
Serialize all tasks in this group through a strand when set to
true.Periodic tasks skip overlapping executions for the same task instance, while one-shot tasks are queued and executed sequentially.
-
Group parent_group = ""
Optional parent group name whose execution context should be reused.
When the parent group is serial, this group also runs serially through the parent strand.
-
PreExecuteCallback pre_execute_callback = nullptr
Optional group pre-execute callback applied to all tasks in the group.
-
PostExecuteCallback post_execute_callback = nullptr
Optional group post-execute callback applied to all tasks in the group.
-
bool enable_serial_execution = false
-
struct StartConfig
Startup configuration for the scheduler worker threads.
Public Members
- std::vector< ThreadConfig > worker_configs = { ThreadConfig{.name = "Worker",.stack_size = 6 * 1024,}}
Worker thread configurations used when the scheduler starts.
The default configuration creates a single worker named
Workerwith a 6 KiB stack.
-
size_t worker_poll_interval_ms = 10
Worker polling interval in milliseconds.
-
PreExecuteCallback pre_execute_callback = nullptr
Optional global pre-execute callback applied to every task.
The callback fires just before any task executes, regardless of group membership.
-
PostExecuteCallback post_execute_callback = nullptr
Optional global post-execute callback applied to every task.
The callback fires after any task completes, regardless of group membership.
-
struct Statistics
Aggregate counters for task execution.
Public Members
-
size_t total_tasks = {0}
Total number of tasks ever scheduled.
-
size_t completed_tasks = {0}
Number of tasks that completed successfully.
-
size_t failed_tasks = {0}
Number of tasks that finished unsuccessfully.
-
size_t canceled_tasks = {0}
Number of tasks canceled before completion.
-
size_t suspended_tasks = {0}
Number of tasks currently suspended.
-
size_t total_tasks = {0}
-
enum class TaskType