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() or dispatch().

enumerator Delayed

One-shot timer task scheduled with post_delayed().

enumerator Periodic

Repeating timer task scheduled with post_periodic().

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.

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 false stops 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

true on success, or false when startup fails.

inline bool start()

Start the scheduler with the default configuration.

Returns

true on success, or false when 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

true when worker threads and the io_context are active, or false otherwise.

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

true if the group was configured successfully, or false otherwise.

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

true if the task was scheduled successfully, or false otherwise.

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

true if the task was scheduled successfully, or false otherwise.

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

true if the task was scheduled successfully, or false otherwise.

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 false stops 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

true if the task was scheduled successfully, or false otherwise.

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

true if all tasks were scheduled successfully, or false otherwise.

void cancel(TaskId id)

Cancel a task by ID.

Parameters

id[in] Task ID to cancel.

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

true if the task was suspended successfully, or false otherwise.

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

true if the task was resumed successfully, or false otherwise.

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. -1 waits indefinitely.

Returns

true if the task completed within the timeout, or false otherwise.

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. -1 waits indefinitely.

Returns

true if all tasks in the group completed within the timeout, or false otherwise.

bool wait_all(int timeout_ms = -1)

Wait for all tasks to complete.

Parameters

timeout_ms[in] Timeout in milliseconds. -1 waits indefinitely.

Returns

true if all tasks completed within the timeout, or false otherwise.

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

true if the timer restarted successfully, or false when 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::Immediate when 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::Finished when 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

Statistics structure 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 nullptr when 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.

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 Worker with 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.