XTimer - A Lightweight Timer Implementation
XTimer
Section titled “XTimer”Path: src/modbus/xtimer.h
Revision History:
- Initial documentation
A lightweight, template-based timer implementation designed for embedded systems, specifically targeting ESP-32. The timer provides functionality for scheduling tasks to run after a delay, at a specific time, or at regular intervals. It avoids using the standard library, making it suitable for resource-constrained environments.
REQUIREMENTS
Section titled “REQUIREMENTS”- No specific hardware pins required
- C++17 support
- Arduino framework or equivalent (
millis()
function)
PROVIDES
Section titled “PROVIDES”Timer<size_t max_tasks, unsigned long (*time_func)()>
- Main timer class templatehandler_t
- Function pointer type for task callbackstimer_create_default()
- Utility function to create a timer with default settingstask
struct - Internal structure to represent scheduled tasks
FEATURES
Section titled “FEATURES”- Schedule tasks to run after a specified delay
- Schedule tasks to run at specific time points
- Schedule recurring tasks at regular intervals
- Configurable number of maximum concurrent tasks
- Customizable time function (defaults to
millis()
) - Small memory footprint with fixed-size task array
- No dynamic memory allocation
DEPENDENCIES
Section titled “DEPENDENCIES”src/modbus/macros.h
- Arduino core (
Arduino.h
orWProgram.h
for older versions)
BEHAVIOUR
Section titled “BEHAVIOUR”The timer operates by tracking tasks and their scheduled execution times:
PERFORMANCE
Section titled “PERFORMANCE”- Consider a more efficient data structure than a simple array for tasks, especially for systems with many scheduled tasks
- Implement a priority queue to optimize the
tick()
function when handling many tasks - Provide options to reduce memory usage for systems with very limited RAM
SECURITY
Section titled “SECURITY”- No major security concerns as this is a local timer implementation
- Ensure task handlers do not introduce timing vulnerabilities in security-critical applications
COMPLIANCE
Section titled “COMPLIANCE”- Review for MISRA C++ compliance if used in safety-critical applications
- Ensure thread safety if used in multi-threaded environments
RECOMMENDATIONS
Section titled “RECOMMENDATIONS”- Keep task handlers lightweight to avoid blocking the main loop
- Avoid using too many concurrent tasks as it may impact performance
- For time-critical operations, consider using hardware timers instead
- When using the
every()
function for periodic tasks, be aware of potential timing drift over long periods - Consider implementing a task ID return value to allow for cancellation of scheduled tasks