HomeAbout UsContact Us

Fixing FreeRTOS Timer Task Stall When Command Queue Is Full

By Jithin Tom
Published in Embedded OS
November 17, 2026
13 min read
Fixing FreeRTOS Timer Task Stall When Command Queue Is Full

Table Of Contents

01
The Symptom: Timer Callbacks Stop Executing
02
What the Timer Task Actually Does
03
Root Cause Analysis: The Three Stall Mechanisms
04
The Command Queue Structure & Internals
05
Solution 1: Raise Timer Task Priority (Immediate Fix)
06
Solution 2: Sizing Methodology and Queue Monitoring
07
Solution 3: Decouple Callbacks from Timer APIs (Architectural Fix)
08
Verification Checklist & Stress Test Matrix
09
Debugging When It Happens in Production
10
Summary
11
Related Reading
12
References
13
Frequently Asked Questions

Your FreeRTOS application runs reliably for hours, then software timer callbacks stop firing. The tick interrupt may still advance the kernel tick count, and other tasks may continue to run. Meanwhile, one-shot timers cannot be restarted or timer API calls begin to fail with pdFAIL (sometimes named errQUEUE_FULL) or wait for queue capacity.

In a debugger, the timer command queue (xTimerQueue) may be full (uxMessagesWaiting == uxLength). That snapshot is a symptom, not a diagnosis: the timer service task (prvTimerTask) might be blocked while trying to send to its own queue, starved of CPU time, or spending too long inside a timer or pended-function callback. A timer daemon legitimately waiting for the next command or expiry is also often in eBlocked; the call stack and wait object distinguish healthy waiting from a problem.

This guide examines the FreeRTOS timer service architecture, explains three related failure mechanisms, and shows how to prevent queue pressure and diagnose stalls. The examples primarily assume a single-core, preemptive FreeRTOS configuration; scheduling and instrumentation must be adapted for SMP ports and vendor-maintained kernel versions.

The Symptom: Timer Callbacks Stop Executing

The symptoms differ depending on whether a callback waits on a full queue, the daemon cannot obtain CPU time, or an individual non-blocking command is rejected:

Diagnostic IndicatorCallback Wait on Full QueuePriority StarvationZero-Wait Command Rejection
Timer Daemon StateeBlocked on the queue’s send-wait list until timeout; potentially indefinitelyOften eReady but not scheduledAny legitimate state; usually still functioning
xTimerQueue StateFull when the send is attemptedCan fill as commands accumulateFull at the failed send; may be transient
API Return ValuesFinite waits eventually return pdFAIL if still full; an indefinite wait may not returnWaiting callers can time out; zero-wait callers may failAffected calls immediately return pdFAIL
Callback ExecutionPaused while daemon waits; permanently stalled only with indefinite blockingDelayed or stopped while starvation persistsOther callbacks can continue; a particular re-arm may be lost
Tick InterruptMay continue normallyMay continue normallyMay continue normally

Consider a one-shot timer incorrectly re-armed from its own callback:

/* Anti-pattern: blocking timer command from the timer daemon task. */
static void vSensorTimerCallback( TimerHandle_t xTimer )
{
/* If the timer queue is full, this can block the entire daemon
* for up to 10 ticks; the timer daemon cannot drain its queue
* while blocked inside this call. */
BaseType_t xStatus = xTimerReset( xTimer, ( TickType_t ) 10U );
if( xStatus != pdPASS )
{
/* This one-shot timer was not re-armed by this command. */
}
}
/* Call from a task after the scheduler has started. */
void vStartSensorSubsystem( void )
{
TimerHandle_t xTimer = xTimerCreate( "SensorTmr",
pdMS_TO_TICKS( 100U ),
pdFALSE, /* One-shot timer. */
NULL,
vSensorTimerCallback );
configASSERT( xTimer != NULL );
if( xTimer != NULL )
{
BaseType_t xStartStatus = xTimerStart( xTimer, pdMS_TO_TICKS( 20U ) );
configASSERT( xStartStatus == pdPASS );
( void ) xStartStatus;
}
}

Software timer callbacks execute in the FreeRTOS timer service task, not an ISR and not the task that originally started the timer. When vSensorTimerCallback() sends a command, the daemon is both the producer and the only consumer of xTimerQueue.

If the queue is full, xTimerReset( xTimer, 10 ) can block the daemon for up to 10 ticks, then return failure if no other actor removes an item. A finite timeout is thus a temporary self-stall, not necessarily a permanent deadlock. An indefinite wait, typically portMAX_DELAY when INCLUDE_vTaskSuspend == 1, can cause a persistent self-deadlock because the daemon cannot run its own dequeue loop. Avoid non-zero queue-send block times inside timer callbacks regardless of the configured timeout.

What the Timer Task Actually Does

The main control loop in FreeRTOS-Kernel/timers.c follows this pattern (a condensed illustration, not a verbatim kernel source excerpt):

static portTASK_FUNCTION( prvTimerTask, pvParameters )
{
TickType_t xNextExpireTime;
BaseType_t xListWasEmpty;
( void ) pvParameters;
#if ( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 )
vApplicationDaemonTaskStartupHook();
#endif
for( ; ; )
{
xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty );
prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty );
prvProcessReceivedCommands();
}
}

The architecture consists of three sequential phases:

  1. Next Expiry Calculation: prvGetNextExpireTime() inspects the current ordered active-timer list. FreeRTOS maintains separate current and overflow lists to account for tick-count wraparound.
  2. Timer Processing and Blocking: prvProcessTimerOrBlockTask() suspends scheduling while sampling the tick count and deciding whether to process an expiry or wait. If a timer is due, the daemon resumes scheduling and processes an expired timer; otherwise it waits on xTimerQueue until an earlier command arrives, the next expiry is due, or the tick count wraps. Timers are processed one at a time as the loop progresses, with additional expiry handling during tick overflow.
  3. Command Queue Draining: prvProcessReceivedCommands() repeatedly calls xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) while messages are available. Processing a command may itself execute a user callback or a deferred (pended) function.

Normal auto-reload expirations do not enqueue timer commands. The kernel normally reschedules auto-reload timers by updating the active timer lists internally (prvReloadTimer() and related list helpers). A delayed daemon can cause callbacks to execute late or in a catch-up sequence; native auto-reload does not guarantee zero jitter.

Queue traffic comes from timer control APIs such as xTimerStart(), xTimerReset(), xTimerChangePeriod(), xTimerStop(), xTimerDelete(), their applicable *FromISR() variants, and xTimerPendFunctionCall() / xTimerPendFunctionCallFromISR() when enabled. A successful API return means the command was queued, not necessarily processed.

Root Cause Analysis: The Three Stall Mechanisms

This diagram shows the distinct producers of timer-queue commands and the critical callback feedback path:

APPLICATION TASKS INTERRUPTS
xTimerStart/Reset/... xTimerResetFromISR(...)
xTimerPendFunctionCall(...) xTimerPendFunctionCallFromISR(...)
| |
| Task send: optional wait | ISR send: no wait
+------------------+------------------+
v
+---------------------------+
| xTimerQueue (bounded) |
| Timer and pended calls |
+---------------------------+
|
| non-blocking receive
v
+---------------------------+
| prvTimerTask |
| 1. Determine next expiry |
| 2. Wait / run callbacks |
| 3. Process queued cmds |
+---------------------------+
| |
Timer callback Pended function
| |
+------+-------+
|
Sending another timer
command to a FULL queue
|
+-----------------+------------------+
| |
zero block time non-zero block time
-> send fails -> daemon itself waits
(bounded or indefinite)

On a single-core system, the timer service task is the sole consumer. While it is blocked inside a callback, no other task can drain this queue. While it is merely starved of CPU time, commands can continue accumulating until the queue becomes full.

Mechanism 1: Self-Deadlock via Callback Blocking

A timer or pended-function callback that sends to xTimerQueue with a non-zero wait can stall the very task that must free queue space:

static void vBadCallback( TimerHandle_t xTimer )
{
/* A full queue can deadlock the daemon indefinitely if
* portMAX_DELAY means 'wait forever' in this configuration. */
( void ) xTimerReset( xTimer, portMAX_DELAY );
}
  1. prvTimerTask invokes the callback while servicing an expiry or a queued command.
  2. xTimerReset() routes through xTimerGenericCommandFromTask(), which attempts a queue send using xQueueSendToBack().
  3. If the queue is full, the daemon itself joins the queue’s waiting-to-send list.
  4. The daemon cannot reach prvProcessReceivedCommands() to make space while it remains blocked.
  5. With a finite timeout, the send can fail and the daemon resumes after the timeout. With portMAX_DELAY and INCLUDE_vTaskSuspend == 1, this wait can be indefinite unless some external intervention unblocks the task.

Result: either a bounded global timer-service stall or, under an indefinite wait, a self-deadlock. The same issue applies to blocking pended-function callbacks, even when they do not manipulate software timers directly.

Mechanism 2: Silent Timer Abandonment via Zero Wait

A zero wait avoids blocking the daemon but requires explicit failure handling:

static void vZeroWaitCallback( TimerHandle_t xTimer )
{
if( xTimerReset( xTimer, 0U ) != pdPASS )
{
/* Re-arm request not queued: record/report this failure. */
}
}
  1. If the queue is full at the time of the send, xQueueSendToBack( ..., 0 ) fails immediately (normally pdFAIL, also known as errQUEUE_FULL).
  2. No reset command is queued; checking the return value is essential. FreeRTOS does not automatically retry a rejected timer command.
  3. For a one-shot timer that has already expired, losing its only re-arm request leaves it dormant unless another task later restarts it.
  4. Other timers and callbacks can still run. A single dropped command is not equivalent to a frozen timer daemon.

Prefer a native auto-reload timer for periodic work, or arrange for a worker task to retry or handle failed re-arm requests according to the application’s requirements.

Mechanism 3: Daemon Task Starvation (Scheduling Priority)

Here, the issue is CPU starvation, not classic mutex-related priority inversion. A ready higher-priority task that never blocks can prevent the timer service task from running on a single-core, preemptive FreeRTOS system:

/* Illustrative FreeRTOSConfig.h settings. */
#define configMAX_PRIORITIES 8
#define configTIMER_TASK_PRIORITY 2

If continuously ready application tasks execute at priorities 3, 4 or 5:

  1. The timer daemon can remain Ready but receive little or no CPU time.
  2. Application tasks or ISRs may continue enqueueing timer commands or pended-function calls.
  3. Commands accumulate because the daemon cannot process them.
  4. Eventually, the queue can fill; zero-wait calls then fail, and finite-wait calls can time out.
  5. Even with no full queue, expired timer callbacks can run late because they require daemon CPU time.

Equal-priority tasks do not automatically cause starvation: their behavior depends on time slicing, yields, blocking behavior and port scheduling. On SMP kernels, core affinity and other runnable work also affect scheduling.

The Command Queue Structure & Internals

FreeRTOS does not export xTimerQueue as a public application handle. In the kernel’s timers.c, it has file-scope static linkage:

PRIVILEGED_DATA static QueueHandle_t xTimerQueue = NULL;

Each queue slot contains a DaemonTaskMessage_t. The relevant layout in the current upstream implementation is:

/* Internal kernel types; not public application interfaces. */
typedef struct tmrTimerParameters
{
TickType_t xMessageValue;
Timer_t * pxTimer;
} TimerParameter_t;
typedef struct tmrCallbackParameters
{
portTIMER_CALLBACK_ATTRIBUTE PendedFunction_t pxCallbackFunction;
void * pvParameter1;
uint32_t ulParameter2;
} CallbackParameters_t;
typedef struct tmrTimerQueueMessage
{
BaseType_t xMessageID;
union
{
TimerParameter_t xTimerParameters;
#if ( INCLUDE_xTimerPendFunctionCall == 1 )
CallbackParameters_t xCallbackParameters;
#endif
} u;
} DaemonTaskMessage_t;

The command identifiers are defined in FreeRTOS-Kernel/include/timers.h, including negative IDs for pended-function calls:

#define tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR ( ( BaseType_t ) -2 )
#define tmrCOMMAND_EXECUTE_CALLBACK ( ( BaseType_t ) -1 )
#define tmrCOMMAND_START_DONT_TRACE ( ( BaseType_t ) 0 )
#define tmrCOMMAND_START ( ( BaseType_t ) 1 )
#define tmrCOMMAND_RESET ( ( BaseType_t ) 2 )
#define tmrCOMMAND_STOP ( ( BaseType_t ) 3 )
#define tmrCOMMAND_CHANGE_PERIOD ( ( BaseType_t ) 4 )
#define tmrCOMMAND_DELETE ( ( BaseType_t ) 5 )
#define tmrFIRST_FROM_ISR_COMMAND ( ( BaseType_t ) 6 )
#define tmrCOMMAND_START_FROM_ISR ( ( BaseType_t ) 6 )
#define tmrCOMMAND_RESET_FROM_ISR ( ( BaseType_t ) 7 )
#define tmrCOMMAND_STOP_FROM_ISR ( ( BaseType_t ) 8 )
#define tmrCOMMAND_CHANGE_PERIOD_FROM_ISR ( ( BaseType_t ) 9 )

On a typical 32-bit Cortex-M ABI with 32-bit function pointers, BaseType_t, pointers and tick values, sizeof( DaemonTaskMessage_t ) is usually 12 bytes with INCLUDE_xTimerPendFunctionCall == 0, or 16 bytes when it is enabled. Check sizeof in your actual toolchain; other ABIs and attributes can change these figures. Queue storage also includes internal queue metadata.

configTIMER_QUEUE_LENGTH is a project configuration value, not a universal FreeRTOS default of 10. If it is configured as 10, ten messages can be queued concurrently, regardless of the number of software timers created. A timer can be active without occupying a command-queue slot.

Solution 1: Raise Timer Task Priority (Immediate Fix)

If profiling shows scheduler starvation, give the timer daemon enough priority to meet its callback and command-service latency requirements. There is no universally safe highest-priority setting: the choice must follow the application’s deadline analysis.

/* FreeRTOSConfig.h - illustrative single-core configuration. */
#define configMAX_PRIORITIES 8
#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 )
#define configTIMER_QUEUE_LENGTH 25

This example gives the daemon priority 7 and allocates 25 command slots; neither value is a universal recommendation. Raising priority does not fix a timer callback that blocks indefinitely, and a bigger queue does not cure sustained overload.

Why This Eliminates Starvation

When an application task enqueues a command while the timer service task is waiting for queue input, the enqueue operation can make the daemon Ready. On a single-core preemptive scheduler, a newly Ready daemon with strictly higher priority than the running task can preempt that task at the next permitted scheduling point. ISR send APIs can similarly request a switch on ISR exit through pxHigherPriorityTaskWoken and the port’s yield mechanism.

The daemon then handles timer expiries and queued commands in its service loop. This reduces scheduling-related queue latency, but it does not guarantee an immediate switch in critical sections, during interrupt masking, when a still-higher-priority task is running, or on all SMP configurations. There is no guaranteed one-message maximum queue depth: bursts of producers, higher-priority interrupts, and time spent inside callbacks can fill a queue even when the daemon has high priority.

[!WARNING] Increasing the timer task priority also increases the scheduling impact of every timer callback and pended function. A callback that consumes 10 ms of CPU at a high priority can delay lower-priority tasks by roughly that amount (and possibly longer with repeated callbacks). Determine a callback time budget from your real-time deadlines; do not assume a universal microsecond limit.

Tiered Priority Scheme for Safety-Critical Systems

In systems with safety, control-loop and communication deadlines, assign priorities based on worst-case response-time analysis rather than placing the timer task above every other task. A software timer callback is not a substitute for a hardware-timed control loop when hard deadlines demand lower latency and jitter.

One possible illustrative hierarchy is:

/* FreeRTOSConfig.h / application priority definitions. */
#define configMAX_PRIORITIES 8
/* Level 7: Safety-critical monitoring/control (if analysis requires it). */
#define SAFETY_SUPERVISOR_PRIORITY ( configMAX_PRIORITIES - 1 )
/* Level 6: Hard-deadline control work handled by a dedicated task. */
#define MOTOR_CONTROL_TASK_PRIORITY ( configMAX_PRIORITIES - 2 )
/* Level 5: Software timer daemon, higher than ordinary workers. */
#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 3 )
/* Levels 1-4: Less time-critical application work. */
#define APP_WORKER_PRIORITY 3
#define APP_COMM_PRIORITY 2
#define APP_LOGGER_PRIORITY 1

Here the timer daemon has priority 5, so ordinary application tasks cannot starve it, but the highest-priority control work can preempt it. Sustained activity at levels 6 or 7 can still delay timers: prove their CPU budgets leave enough service time. Watchdog servicing also needs a deliberate design: assigning the watchdog task top priority is not, by itself, evidence that the rest of the system is healthy or compliant with a safety standard.

Runtime Verification in Idle Hook

A lightweight idle-hook check can catch an unexpectedly changed daemon priority when the idle hook gets CPU time. It cannot diagnose starvation during a busy interval, because the idle task itself will not run then. xTimerGetTimerDaemonTaskHandle() should be called only after the timer task has been created; current upstream kernels assert if its handle is null. Enable the required idle hook and task-priority query options in your configuration.

/* Requires configUSE_IDLE_HOOK == 1 and INCLUDE_uxTaskPriorityGet == 1.
* Run after the scheduler has started; single-core example. */
void vApplicationIdleHook( void )
{
static BaseType_t xChecked = pdFALSE;
if( xChecked == pdFALSE )
{
TaskHandle_t xDaemon = xTimerGetTimerDaemonTaskHandle();
configASSERT( xDaemon != NULL );
configASSERT( uxTaskPriorityGet( xDaemon ) == configTIMER_TASK_PRIORITY );
xChecked = pdTRUE;
}
}

To detect runtime starvation, use task execution traces or a bounded-rate monitor in an appropriately scheduled diagnostic task. If your application intentionally changes daemon priority with vTaskPrioritySet(), validate against the updated intended value rather than the compile-time constant.

Solution 2: Sizing Methodology and Queue Monitoring

Size the timer command queue for commands that may be outstanding simultaneously. Timer expiries themselves do not enqueue messages. The queue holds requests from tasks, ISRs and enabled pended-function APIs; commands created by callbacks can add pressure but should normally be eliminated.

No queue capacity can compensate for an unbounded command rate if the daemon cannot keep up. Estimate the worst credible burst and verify the result under the actual interrupt and task load.

Worst-Case Queue Sizing Formula

As a first-order engineering bound, account for commands that arrive together plus commands that can arrive while the daemon is unable to dequeue:

L_queue >= B_simultaneous + ceil( R_peak * T_no_service ) + M_headroom

Where:

  • B_simultaneous: Maximum simultaneous burst from task and ISR producers, including pended-function requests and any legacy callback-generated timer commands not already counted.
  • R_peak: Maximum additional command arrival rate during the no-service interval (commands/tick). Use a proven peak envelope, not a long-term average.
  • T_no_service: Worst credible interval (ticks) during which the daemon cannot dequeue, including higher-priority execution and callback processing.
  • M_headroom: Engineering margin selected from workload variability and measurements; there is no kernel-defined minimum of five slots.

Avoid counting periodic timer expiries as command arrivals. The formula is an illustrative upper-bound estimate, not a schedulability proof: bursts can overlap, the dequeue/processing rate matters, and timing may need analysis at finer-than-tick resolution. Measure high-water occupancy and enqueue failures under stress.

Compile-Time Validation Header

If you can express the chosen workload bound as integer counts and tick intervals, enforce the chosen queue capacity at build time. The values below are example workload assumptions, not FreeRTOS requirements:

/* timer_queue_config.h - include AFTER the relevant config macros. */
#ifndef TIMER_QUEUE_CONFIG_H
#define TIMER_QUEUE_CONFIG_H
#define MAX_SIMULTANEOUS_COMMANDS 8
#define PEAK_COMMANDS_PER_TICK 4
#define MAX_NO_SERVICE_TICKS 3
#define QUEUE_SAFETY_MARGIN 10
/* Illustrative bound: 8 + (4 * 3) + 10 = 30 slots. */
#define CALCULATED_MIN_TIMER_QUEUE_LEN \
( MAX_SIMULTANEOUS_COMMANDS + \
( PEAK_COMMANDS_PER_TICK * MAX_NO_SERVICE_TICKS ) + \
QUEUE_SAFETY_MARGIN )
#if ( configTIMER_QUEUE_LENGTH < CALCULATED_MIN_TIMER_QUEUE_LEN )
#error "Timer command queue shorter than the application's assumed burst bound"
#endif
#endif /* TIMER_QUEUE_CONFIG_H */

The C preprocessor can evaluate the integer expressions used here. Include this header after configTIMER_QUEUE_LENGTH is defined in FreeRTOSConfig.h; otherwise the comparison may falsely treat the undefined macro as zero. If you choose the earlier illustrative queue length of 25, increase it to at least 30 for these particular assumptions, or refine the workload bound using real measurements.

Safe Runtime Queue Depth Monitoring

xTimerQueue is static in timers.c, so application code should not attempt to link against it directly. The queue registry is useful for debugger visibility: with a non-zero configQUEUE_REGISTRY_SIZE, current upstream timers.c registers the queue as "TmrQ". A registry entry is a debugger aid, not a public timer-queue handle.

/* FreeRTOSConfig.h - optional debugger support. */
#define configQUEUE_REGISTRY_SIZE 8
/* In the current upstream kernel the timer queue is registered as "TmrQ".
* Trace hooks can report send failures but do not, by themselves, report
* the current queue depth. */

If runtime occupancy telemetry is essential, a small, version-controlled kernel accessor can expose depth without making the handle public. This code must be added inside timers.c (and declared in an application-maintained header, not assumed to be part of the upstream timers.h API):

/* Local patch to timers.c, within #if ( configUSE_TIMERS == 1 ).
* Call only from task context, after timer-queue initialization. */
UBaseType_t uxTimerGetQueueMessagesWaiting( void )
{
if( xTimerQueue == NULL )
{
return 0U;
}
return uxQueueMessagesWaiting( xTimerQueue );
}

With that accessor declared to your monitor task, record sampled depth and threshold crossings:

/* Application code; initialize these before scheduling the monitor. */
static volatile UBaseType_t uxTimerQueuePeakObserved = 0U;
static volatile uint32_t ulTimerQueuePressureSamples = 0U;
void vTimerQueueWatchdogTask( void * pvParameters )
{
const UBaseType_t uxThreshold =
( ( UBaseType_t ) configTIMER_QUEUE_LENGTH * 80U ) / 100U;
( void ) pvParameters;
for( ; ; )
{
UBaseType_t uxDepth = uxTimerGetQueueMessagesWaiting();
if( uxDepth > uxTimerQueuePeakObserved )
{
uxTimerQueuePeakObserved = uxDepth;
}
if( uxDepth >= uxThreshold )
{
ulTimerQueuePressureSamples++;
}
vTaskDelay( pdMS_TO_TICKS( 250U ) );
}
}

This is sampled, not exact, high-water monitoring: a 250 ms poll can miss very brief bursts or failures. For stronger evidence, instrument enqueue results with traceTIMER_COMMAND_SEND (see below), or use a kernel-aware RTOS trace tool. Take synchronization and counter-overflow requirements into account if these values are accessed by multiple tasks or cores.

Solution 3: Decouple Callbacks from Timer APIs (Architectural Fix)

The most robust design is to keep timer and pended-function callbacks short and non-blocking. For a periodic activity, use a native auto-reload timer; for work requiring I/O, mutexes, lengthy processing or changing timer parameters, signal a worker task instead of performing that work in the daemon.

A callback may legally use timer APIs with zero block time, but doing so is more fragile under queue pressure. A design that does not generate timer commands from callbacks avoids this particular feedback path altogether.

[!IMPORTANT] Software timer callbacks run in task context, not interrupt context. Call xTaskNotifyGive() or task-level xQueueSend() as appropriate; do not use *FromISR() variants from a timer callback. Those variants have ISR-specific assumptions and are not the correct API for daemon-task code. Task notifications do not take a wait time; for queue/semaphore APIs called in callbacks, use a zero block time and handle failures.

Pattern A: Direct Task Notification from Callback

A direct-to-task notification is a low-overhead way to wake an application worker without writing to the timer command queue. In this example pdFALSE makes ulTaskNotifyTake() decrement the notification count by one, so multiple expiries can be handled separately rather than deliberately clearing all pending counts.

/* Requires configUSE_TASK_NOTIFICATIONS == 1. */
static TaskHandle_t xSensorWorkerTaskHandle = NULL;
static void vSensorTimerCallback( TimerHandle_t xTimer )
{
( void ) xTimer;
/* xTaskNotifyGive() is a task-context API; it does not block. */
if( xSensorWorkerTaskHandle != NULL )
{
( void ) xTaskNotifyGive( xSensorWorkerTaskHandle );
}
}
void vSensorWorkerTask( void * pvParameters )
{
TimerHandle_t xTimer;
( void ) pvParameters;
xSensorWorkerTaskHandle = xTaskGetCurrentTaskHandle();
xTimer = xTimerCreate( "SensorTmr",
pdMS_TO_TICKS( 50U ),
pdTRUE, /* Native auto-reload. */
NULL,
vSensorTimerCallback );
configASSERT( xTimer != NULL );
if( xTimer == NULL )
{
/* Requires INCLUDE_vTaskDelete == 1. */
vTaskDelete( NULL );
return;
}
BaseType_t xStartStatus = xTimerStart( xTimer, pdMS_TO_TICKS( 20U ) );
configASSERT( xStartStatus == pdPASS );
( void ) xStartStatus;
for( ; ; )
{
( void ) ulTaskNotifyTake( pdFALSE, portMAX_DELAY );
/* Sensor I/O and any timer period changes belong here,
* in an application task rather than in the daemon. */
vSampleSensorHardware(); /* Application-supplied function. */
}
}

The example assumes a valid non-zero timer period, a working scheduler and application-provided vSampleSensorHardware(). Check and handle the start-command result in production even when assertions are compiled out. Notification counts have finite width, so if the worker falls behind for long enough, use explicit overload handling rather than treating every timer tick as guaranteed delivered.

Pattern B: Dedicated Application Command Queue

When timers report distinct events to one controller, a separate application queue keeps event delivery separate from FreeRTOS timer control. Create the queue before starting the timer, and explicitly track a full application queue:

typedef enum
{
APP_EVENT_TIMER_SAMPLE_TICK,
APP_EVENT_TIMER_WATCHDOG_PING,
APP_EVENT_TIMER_HEARTBEAT
} AppTimerEvent_t;
static QueueHandle_t xAppEventQueue = NULL;
static volatile uint32_t ulAppEventDrops = 0U;
static void vTelemetryTimerCallback( TimerHandle_t xTimer )
{
const AppTimerEvent_t xEvent = APP_EVENT_TIMER_SAMPLE_TICK;
( void ) xTimer;
if( xQueueSend( xAppEventQueue, &xEvent, 0U ) != pdPASS )
{
/* Bounded queue is full: the event was not delivered. */
ulAppEventDrops++;
}
}
void vApplicationControllerTask( void * pvParameters )
{
AppTimerEvent_t xEvent;
TimerHandle_t xTelemetryTimer;
( void ) pvParameters;
xAppEventQueue = xQueueCreate( 16U, sizeof( AppTimerEvent_t ) );
configASSERT( xAppEventQueue != NULL );
if( xAppEventQueue == NULL )
{
vTaskDelete( NULL );
return;
}
xTelemetryTimer = xTimerCreate( "Telemetry",
pdMS_TO_TICKS( 100U ),
pdTRUE,
NULL,
vTelemetryTimerCallback );
configASSERT( xTelemetryTimer != NULL );
if( xTelemetryTimer == NULL )
{
vTaskDelete( NULL );
return;
}
BaseType_t xStartStatus = xTimerStart( xTelemetryTimer,
pdMS_TO_TICKS( 20U ) );
configASSERT( xStartStatus == pdPASS );
( void ) xStartStatus;
for( ; ; )
{
if( xQueueReceive( xAppEventQueue, &xEvent, portMAX_DELAY ) == pdPASS )
{
switch( xEvent )
{
case APP_EVENT_TIMER_SAMPLE_TICK:
vProcessTelemetrySampling(); /* Application function. */
break;
case APP_EVENT_TIMER_WATCHDOG_PING:
vServiceApplicationWatchdog(); /* Application function. */
break;
case APP_EVENT_TIMER_HEARTBEAT:
/* Optional heartbeat event. */
break;
default:
break;
}
}
}
}

The example assumes successful initialization (assertions enabled); production code must provide a defined recovery path for allocation or enqueue failures. This removes timer-queue writes from the callback, not all possible data loss: the separate event queue is bounded and can still overflow. For events that can be coalesced, a task notification may be simpler than an application queue.

Pattern C: Native Auto-Reload Instead of Manual Reset

For genuinely periodic work, avoid manually restarting a one-shot timer in its callback:

/* Less robust: one timer-queue command for every period. */
static void vBadReloadCallback( TimerHandle_t xTimer )
{
( void ) xTimerStart( xTimer, 0U );
/* If the command fails, no automatic retry occurs. */
}
/* Preferred: the kernel reloads this timer internally. */
static void vCleanCallback( TimerHandle_t xTimer )
{
( void ) xTimer;
/* Signal a worker or perform another short, non-blocking action. */
}
void vCreatePeriodicTimer( void )
{
TimerHandle_t xAuto = xTimerCreate( "Auto",
pdMS_TO_TICKS( 100U ),
pdTRUE,
NULL,
vCleanCallback );
configASSERT( xAuto != NULL );
if( xAuto != NULL )
{
BaseType_t xStartStatus = xTimerStart( xAuto, 0U );
configASSERT( xStartStatus == pdPASS );
( void ) xStartStatus;
}
}

pdTRUE in the xTimerCreate() auto-reload argument lets the kernel schedule subsequent expiries using its internal timer lists rather than a new timer command on each expiry. This is appropriate for periodic behavior; a one-shot timer remains the right choice for irregular schedules and explicit inactivity timeouts.

Timer Callback Design Rules

==========================================================================
FREERTOS SOFTWARE TIMER CALLBACK DESIGN RULES
==========================================================================
1. PREFER ZERO TIMER-COMMAND TRAFFIC
Use native auto-reload for periodic work. Timer APIs in callbacks are
permitted with zero queue wait, but check every return value; never use
a non-zero wait that can block the daemon on its own queue.
2. NEVER BLOCK THE TIMER DAEMON
Do not call vTaskDelay, blocking mutex/semaphore operations, or queue
send/receive operations with non-zero wait from timer callbacks.
3. USE TASK-CONTEXT APIS
Software timer callbacks are task functions, not ISRs. Use xTaskNotifyGive
or xQueueSend(..., 0), not xTaskNotifyFromISR or xQueueSendFromISR.
4. KEEP CALLBACK EXECUTION BOUNDED
Derive a measured execution-time budget from all timer deadlines and
daemon service latency. Defer long I/O, parsing and computation to tasks.
5. AVOID WAITING FOR MUTEXES
A zero-timeout mutex take can fail safely if checked, but waiting
on a contended mutex can stall every timer and deferred function.
==========================================================================

Apply the same non-blocking rules to callbacks scheduled with xTimerPendFunctionCall(); they also execute in the timer daemon task.

Verification Checklist & Stress Test Matrix

Validate the design under realistic task priorities, interrupt rates, critical-section timing and expected bursts. The durations below are sample test plans, not proofs that a specific timer service latency or jitter bound has been met:

ScenarioTest ConditionsDurationExpected ResultPass Criteria
Baseline Idle10 active auto-reload timers (10 ms to 1 s)2 hoursCallbacks occur at expected rates, with bounded tick/scheduler jitterMeasured callback latency within application limits; no enqueue failures
ISR StormControlled ISR burst using xTimerResetFromISR() at a rate within the intended device envelope1 hourTimer commands are accepted at the designed peak rateZero unexpected enqueue failures; measured high-water occupancy within capacity
Preemption Stress4 CPU-bound worker tasks below timer-daemon priority, plus bounded higher-priority interrupts4 hoursDaemon runs during available preemption pointsWorst-case callback lateness within specified deadline
Burst Reset15 period-change requests issued together from tasks15 minAll expected commands enqueue and are later appliedEvery return checked; no unexplained loss or deadline violation
72-Hour SoakFull application at relevant temperature, input and CPU stress72 hoursTimers and task progress continue without a stallNo persistent queue saturation; meaningful heartbeat and watchdog checks pass

A periodic timer’s callback is subject to tick granularity, scheduler delays and execution-time variation; zero jitter is not a realistic general pass criterion. Likewise, a queue-depth sample of zero does not prove that bursts or failed enqueues never occurred.

Automated Self-Test Harness

This representative single-core target test creates 16 auto-reload timers, verifies that callbacks continue progressing during a 30-second window, then queues deletion of the timers. Run it from an application task after the scheduler starts (not from a timer callback), with assertions enabled. It assumes pdMS_TO_TICKS( 10 ) is non-zero and an adequately sized timer command queue.

#include <stdint.h>
#define TEST_TIMER_COUNT 16U
static volatile uint32_t ulCallbackCount[ TEST_TIMER_COUNT ] = { 0U };
static void vStressTestCallback( TimerHandle_t xTimer )
{
intptr_t lTimerID = ( intptr_t ) pvTimerGetTimerID( xTimer );
if( ( lTimerID >= 0 ) && ( lTimerID < ( intptr_t ) TEST_TIMER_COUNT ) )
{
ulCallbackCount[ ( size_t ) lTimerID ]++;
}
}
void vRunTimerStressVerification( void )
{
TimerHandle_t xTimers[ TEST_TIMER_COUNT ];
uint32_t ulPrevious[ TEST_TIMER_COUNT ] = { 0U };
configASSERT( pdMS_TO_TICKS( 10U ) > 0U );
for( size_t i = 0U; i < TEST_TIMER_COUNT; i++ )
{
TickType_t xPeriod = pdMS_TO_TICKS( 10U + ( uint32_t ) i * 5U );
configASSERT( xPeriod > 0U );
xTimers[ i ] = xTimerCreate( "StressTmr",
xPeriod,
pdTRUE,
( void * ) ( intptr_t ) i,
vStressTestCallback );
configASSERT( xTimers[ i ] != NULL );
BaseType_t xStartStatus = xTimerStart( xTimers[ i ],
pdMS_TO_TICKS( 100U ) );
configASSERT( xStartStatus == pdPASS );
( void ) xStartStatus;
}
for( uint32_t second = 0U; second < 30U; second++ )
{
vTaskDelay( pdMS_TO_TICKS( 1000U ) );
for( size_t i = 0U; i < TEST_TIMER_COUNT; i++ )
{
uint32_t ulCurrent;
/* Single-core atomic snapshot; callbacks run in task context. */
taskENTER_CRITICAL();
ulCurrent = ulCallbackCount[ i ];
taskEXIT_CRITICAL();
configASSERT( ulCurrent > ulPrevious[ i ] );
ulPrevious[ i ] = ulCurrent;
}
}
for( size_t i = 0U; i < TEST_TIMER_COUNT; i++ )
{
/* Delete requests are asynchronous; do not reuse the handles. */
BaseType_t xDeleteStatus = xTimerDelete( xTimers[ i ],
pdMS_TO_TICKS( 100U ) );
configASSERT( xDeleteStatus == pdPASS );
( void ) xDeleteStatus;
}
}

The test detects prolonged cessation of callback progress, not all jitter or deadline misses. Add hardware timestamping or an RTOS trace to measure those. configASSERT() may compile out of production builds, so use explicit failure handling for allocations and queue operations in deployable test code. Pointer/integer round-trip encoding of the timer ID is illustrative for the target ABI; production software can instead use a stable object pointer.

Debugging When It Happens in Production

When callbacks stop, capture evidence before resetting the target: timer daemon stack and state, queue occupancy, producer call sites, and whether any pended callback is executing. A full queue alone cannot distinguish overload, scheduling starvation or self-waiting.

Kernel internals, TCB_t layouts and GDB symbol availability vary by FreeRTOS version, compiler optimization and port. Prefer the IDE’s RTOS-aware task/queue views where available.

Diagnostic GDB Commands

With a debug build and symbols for timers.c, these GDB expressions can inspect the upstream-style internal structures. They are debugger queries, not public C API calls:

# 1. Inspect the timer task handle and TCB (single-core kernel example).
(gdb) set $daemon = (TCB_t *)'timers.c'::xTimerTaskHandle
(gdb) print $daemon
(gdb) print $daemon->pcTaskName
(gdb) print $daemon->uxPriority
# There is NO portable TCB field named eCurrentState. Use the RTOS-aware
# Tasks view, a supported eTaskGetState() call, or task-list membership.
# 2. Inspect the private timer command queue.
(gdb) set $tmrq = (Queue_t *)'timers.c'::xTimerQueue
(gdb) print $tmrq->uxMessagesWaiting
(gdb) print $tmrq->uxLength
# 3. Inspect the list of senders waiting for space.
(gdb) print $tmrq->xTasksWaitingToSend.uxNumberOfItems
# If supported by this kernel's debug types, check whether the timer
# task's event list item belongs to the queue's send-wait list.
(gdb) print $daemon->xEventListItem.pxContainer == &$tmrq->xTasksWaitingToSend

If the last comparison is true and the daemon’s call stack is in xQueueGenericSend() reached from a timer or pended callback, it has attempted to send while its own queue was full. Check the timeout argument: a finite wait may recover; an indefinite wait can be a true self-deadlock.

If the queue is full but the daemon is Ready and not executing, investigate higher-priority task execution, disabled interrupts/critical sections, and (for SMP) CPU affinity. If the daemon is Running in a callback, inspect that callback for excessive work, mutex contention and blocking calls. GDB’s 'timers.c':: file-scope syntax and type names may need adjustment for your compiler’s emitted debug symbols.

Lightweight Circular Trace Buffer

For diagnostics without a continuously connected debugger, record whether timer control commands were accepted or rejected using the kernel’s traceTIMER_COMMAND_SEND hook. This macro receives four arguments in the upstream kernel. Pended-function calls use different hooks (tracePEND_FUNC_CALL and tracePEND_FUNC_CALL_FROM_ISR), so this example does not capture their queue traffic. The hook can run from task or ISR context and must not block, print, allocate memory or call task-only RTOS APIs.

/* FreeRTOSConfig.h -- use only if no existing trace implementation owns
* traceTIMER_COMMAND_SEND. Prototype uses plain C types because this
* config header can be parsed before FreeRTOS typedefs are available. */
extern void vRecordTimerTrace( void * pvTimer, int iCommandID, int iResult );
#define traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn ) \
vRecordTimerTrace( ( void * ) ( xTimer ), \
( int ) ( xCommandID ), \
( int ) ( xReturn ) )

A minimal ring buffer for a single-core Cortex-M port supporting the interrupt-mask macros below is:

/* timer_trace.c -- include FreeRTOS.h, task.h, stdint.h and stdio.h. */
#define TIMER_TRACE_ENTRIES 32U
typedef struct
{
uint32_t ulSequence; /* Event order, not a wall-clock timestamp. */
void * pvTimerHandle;
int8_t cCommandID; /* Timer control command ID (normally 0..9). */
uint8_t ucAccepted;
} TimerTraceEntry_t;
static TimerTraceEntry_t xTimerTraceBuffer[ TIMER_TRACE_ENTRIES ];
static volatile uint32_t ulTimerTraceHead = 0U;
void vRecordTimerTrace( void * pvTimer, int iCommandID, int iResult )
{
/* Cortex-M example: protect against concurrent task/ISR writes.
* Replace with port-appropriate synchronization on other ports/SMP. */
UBaseType_t uxMask = portSET_INTERRUPT_MASK_FROM_ISR();
uint32_t ulSeq = ulTimerTraceHead;
uint32_t ulIndex = ulSeq % TIMER_TRACE_ENTRIES;
xTimerTraceBuffer[ ulIndex ].ulSequence = ulSeq;
xTimerTraceBuffer[ ulIndex ].pvTimerHandle = pvTimer;
xTimerTraceBuffer[ ulIndex ].cCommandID = ( int8_t ) iCommandID;
xTimerTraceBuffer[ ulIndex ].ucAccepted =
( iResult == pdPASS ) ? 1U : 0U;
ulTimerTraceHead = ulSeq + 1U;
portCLEAR_INTERRUPT_MASK_FROM_ISR( uxMask );
}

Once logging is stopped, dump the ring in chronological order (or extract it from a crash dump); never call printf() inside the trace hook:

/* Diagnostic task after producers are quiesced; not from an ISR/HardFault. */
void vDumpTimerTraceHistory( void )
{
uint32_t ulHead = ulTimerTraceHead;
uint32_t ulCount = ( ulHead < TIMER_TRACE_ENTRIES ) ?
ulHead : TIMER_TRACE_ENTRIES;
uint32_t ulFirst = ulHead - ulCount;
for( uint32_t i = 0U; i < ulCount; i++ )
{
const TimerTraceEntry_t * pxEntry =
&xTimerTraceBuffer[ ( ulFirst + i ) % TIMER_TRACE_ENTRIES ];
printf( "[%lu] Timer=%p Cmd=%d Enqueue=%s\r\n",
( unsigned long ) pxEntry->ulSequence,
pxEntry->pvTimerHandle,
( int ) pxEntry->cCommandID,
pxEntry->ucAccepted ? "PASS" : "FAIL" );
}
}

In a live system, take a consistent snapshot before printing so concurrent writers do not overwrite entries being read. A recorded failed timer-command enqueue generally indicates a full queue, but the exact interpretation is kernel-version dependent; some earlier failures (such as invalid or absent handles) may return without invoking this hook. The trace result records whether an enqueue succeeded; it does not prove that the daemon processed the command, capture pended-function posts, or pinpoint which caller issued it. Add a producer identifier or use a proper RTOS trace tool when that distinction matters.

Summary

A full FreeRTOS timer command queue indicates that commands or deferred functions are arriving faster than the daemon can service them at that moment. The outcome depends on the caller and the timeout: a zero-wait send can fail without stopping other timers; a finite wait in the daemon can stall all callbacks temporarily; and an indefinite self-wait can cause a persistent deadlock. CPU starvation and excessively long callbacks are additional, distinct causes.

  1. Give the daemon adequate CPU time: Choose configTIMER_TASK_PRIORITY from your scheduling and deadline analysis; do not assume maximum priority is always safe.
  2. Never block inside callbacks: Timer or pended-function callbacks must not wait on a full timer queue or other blocking operations.
  3. Decouple slow work: Use xTaskNotifyGive() or zero-wait application-queue sends to wake worker tasks, and handle overload explicitly.
  4. Use native auto-reload where appropriate: Configure the xAutoReload argument of xTimerCreate() as pdTRUE for genuinely periodic work; it does not generate a reset command on each expiry.
  5. Size and observe real command bursts: Choose configTIMER_QUEUE_LENGTH from a bounded arrival-rate model, measure the high-water mark and enqueue failures, and confirm callback latency under stress.

References

  1. FreeRTOS Kernel API Reference — Software Timers: https://www.freertos.org/Documentation/02-Kernel/04-API-reference/05-Software-timers/00-Software-timers
  2. FreeRTOS Kernel Source Code (timers.c): https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/timers.c
  3. FreeRTOS Kernel Features — Software Timers Architecture: https://www.freertos.org/Documentation/02-Kernel/02-Kernel-features/04-Software-timers/01-Software-timers
  4. FreeRTOS Kernel Book — Chapter 6: Software Timers: https://github.com/FreeRTOS/FreeRTOS-Kernel-Book/blob/main/ch06.md
  5. Percepio Tracealyzer — RTOS Software Timer Analysis & Visualization: https://percepio.com/tracealyzer/
  6. Barry, R., “Mastering the FreeRTOS Real Time Kernel - A Hands On Tutorial Guide”, Real Time Engineers Ltd.

Frequently Asked Questions

Why does the FreeRTOS timer task stall when its command queue is full?

A full timer command queue causes a permanent self-deadlock if the timer daemon task itself waits indefinitely to enqueue a command, for example from a callback using portMAX_DELAY with INCLUDE_vTaskSuspend enabled. A finite non-zero timeout instead stalls the daemon until that timeout expires. Separately, higher-priority CPU-bound tasks can starve the daemon, causing commands to accumulate and time out; equal-priority tasks can delay it depending on scheduling.

How do I know if my timer task is stalled on a full queue?

Inspect the timer daemon's call stack, task state and the private timer queue. A daemon blocked on the queue's send-wait list suggests a callback attempted a blocking send; a finite timeout can recover, whereas an indefinite wait can self-deadlock. A daemon that remains Ready but cannot run suggests starvation. A full queue is evidence of congestion, not proof of the root cause by itself.

What is the root cause of the timer command queue filling up?

The command queue fills when timer commands or pended-function requests arrive faster than the daemon processes them. Contributing factors include bursts from tasks or ISRs, long or blocking timer/pended callbacks, and insufficient daemon CPU time. Ordinary auto-reload expirations do not themselves enqueue timer commands.

Does increasing configTIMER_QUEUE_LENGTH fix the problem?

A longer queue absorbs measured bursts but cannot resolve an indefinitely blocked timer daemon, unbounded producers or sustained starvation. Fix the underlying scheduling or callback behavior first; then size configTIMER_QUEUE_LENGTH for the worst credible command burst with measured headroom.

Can I use task notifications instead of timer command queue writes from callbacks?

Yes, when the design permits it. A software timer callback runs in the timer daemon's task context and may use xTaskNotifyGive() or xQueueSend() with zero wait to signal a worker. Task notifications do not have a blocking timeout argument; for queues, use zero wait and handle a full application queue. Use task APIs, not *FromISR variants.

Tags

freertostimer-taskqueuedeadlockdebuggingrtos

Share


Previous Article
Fixing memcpy Hard Faults on Cortex-M: Unaligned Access Fix
Jithin Tom

Jithin Tom

A Closer Look at C/C++, RTOS, and Embedded Systems

Related Posts

Fixing ThreadX Queue Stack Corruption on STM32
Fixing ThreadX Queue Stack Corruption on STM32
November 13, 2026
11 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media