Skip to content

XTimer - A Lightweight Timer Implementation

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.

  • No specific hardware pins required
  • C++17 support
  • Arduino framework or equivalent (millis() function)
  • Timer<size_t max_tasks, unsigned long (*time_func)()> - Main timer class template
  • handler_t - Function pointer type for task callbacks
  • timer_create_default() - Utility function to create a timer with default settings
  • task struct - Internal structure to represent scheduled tasks
  • 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

XTimer

Macros

Arduino Core

The timer operates by tracking tasks and their scheduled execution times:

Yes

No

Yes

No

Initialize Timer

Add Task to Queue

Timer Tick

Check Task Expiry

Task Expired?

Execute Task Handler

Is Recurring?

Reset Timer for Next Run

Remove Task from Queue

  • 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
  • No major security concerns as this is a local timer implementation
  • Ensure task handlers do not introduce timing vulnerabilities in security-critical applications
  • Review for MISRA C++ compliance if used in safety-critical applications
  • Ensure thread safety if used in multi-threaded environments
  • 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