Software timers in FreeRTOS
How the timer service task keeps its list of active timers, sleeps until the next one is due, runs the callbacks and processes the commands that xTimerStart and xTimerStop send it.
Simulated kernel: FreeRTOS V11.3.3. This scenario and every other one are in the scheduler playground. The simulator and its data files are not covered by the site's CC BY-SA license; see their license notices.
This walkthrough follows the software timers lesson through FreeRTOS’s
timers.c. Everything about software timers in FreeRTOS happens in one task, the timer service
task: other tasks only send it commands. Set the step level
to Line to follow it.
What a timer is
xTimerCreate() allocates a Timer_t and fills it in:
xTimerPeriodInTicks, here 4.ucStatus:tmrSTATUS_IS_AUTORELOADfor an auto-reload timer, andtmrSTATUS_IS_ACTIVEwhile it runs. The timer card in the kernel panel shows both.xTimerListItem: the list item that links it into a list of active timers, with its expiry tick as the item’s value.pxCallbackFunction, the callback.
The first xTimerCreate() also calls prvCheckForValidListAndQueue(), which sets up what the
timer service task works with: two lists of active timers, xActiveTimerList1 and
xActiveTimerList2, and xTimerQueue, the command queue, configTIMER_QUEUE_LENGTH (here 5)
commands long. One list, pxCurrentTimerList, holds the timers due before the tick count wraps,
sorted by expiry; the other holds those due after it. This is the same trick as the two
delayed lists.
The task itself is created by vTaskStartScheduler(), right after the idle task, when
configUSE_TIMERS is 1. It runs at configTIMER_TASK_PRIORITY, 4 here, above every task of the
scenario.
Commands, not calls
main() calls xTimerStart( xBlink, 0 ) before the scheduler starts. That does not start
anything. xTimerStart() is a macro for xTimerGenericCommand() with the command
tmrCOMMAND_START and the tick count of now as its value:
BaseType_t xTimerGenericCommandFromTask( TimerHandle_t xTimer,
const BaseType_t xCommandID,
const TickType_t xOptionalValue,
BaseType_t * const pxHigherPriorityTaskWoken,
const TickType_t xTicksToWait )
{
BaseType_t xReturn = pdFAIL;
DaemonTaskMessage_t xMessage;
( void ) pxHigherPriorityTaskWoken;
traceENTER_xTimerGenericCommandFromTask( xTimer, xCommandID, xOptionalValue, pxHigherPriorityTaskWoken, xTicksToWait );
/* Send a message to the timer service task to perform a particular action
* on a particular timer definition. */
if( ( xTimerQueue != NULL ) && ( xTimer != NULL ) )
{
/* Send a command to the timer service task to start the xTimer timer. */
xMessage.xMessageID = xCommandID;
xMessage.u.xTimerParameters.xMessageValue = xOptionalValue;
xMessage.u.xTimerParameters.pxTimer = xTimer;
/* Enforce a lower bound as well as an upper bound so that only
* valid task-issued commands are accepted here. */
configASSERT( ( xCommandID >= tmrCOMMAND_START_DONT_TRACE ) && ( xCommandID < tmrFIRST_FROM_ISR_COMMAND ) );
if( ( xCommandID >= tmrCOMMAND_START_DONT_TRACE ) && ( xCommandID < tmrFIRST_FROM_ISR_COMMAND ) )
{
if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )
{
xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait );
}
else
{
xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY );
}
}
traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn );
}
else
{
mtCOVERAGE_TEST_MARKER();
}
traceRETURN_xTimerGenericCommandFromTask( xReturn );
return xReturn;
}
timers.c, lines 448–496 · FreeRTOS V11.3.3 · MIT license
The message goes to the back of xTimerQueue with xQueueSendToBack(). Before the scheduler
runs nobody may wait, so it is sent with no block time; from a task it waits for room as long as
the caller allows. In the kernel panel the command shows in the queue as start(Blink, 0).
Sending the tick count of the call matters: when the timer task gets round to the command, it
counts the period from the moment xTimerStart() was called, not from the moment it processes the
command. A start that is processed late still expires on time.
The timer service task
The task’s loop is three lines:
static portTASK_FUNCTION( prvTimerTask, pvParameters )
{
TickType_t xNextExpireTime;
BaseType_t xListWasEmpty;
/* Just to avoid compiler warnings. */
( void ) pvParameters;
#if ( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 )
{
/* Allow the application writer to execute some code in the context of
* this task at the point the task starts executing. This is useful if the
* application includes initialisation code that would benefit from
* executing after the scheduler has been started. */
vApplicationDaemonTaskStartupHook();
}
#endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */
for( ; configCONTROL_INFINITE_LOOP(); )
{
/* Query the timers list to see if it contains any timers, and if so,
* obtain the time at which the next timer will expire. */
xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty );
/* If a timer has expired, process it. Otherwise, block this task
* until either a timer does expire, or a command is received. */
prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty );
/* Empty the command queue. */
prvProcessReceivedCommands();
}
}
timers.c, lines 746–777 · FreeRTOS V11.3.3 · MIT license
prvGetNextExpireTime() reads the head of pxCurrentTimerList: the next timer due, or none.
Then prvProcessTimerOrBlockTask() either runs the timer that is due, or waits:
static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime,
BaseType_t xListWasEmpty )
{
TickType_t xTimeNow;
BaseType_t xTimerListsWereSwitched;
vTaskSuspendAll();
{
/* Obtain the time now to make an assessment as to whether the timer
* has expired or not. If obtaining the time causes the lists to switch
* then don't process this timer as any timers that remained in the list
* when the lists were switched will have been processed within the
* prvSampleTimeNow() function. */
xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );
if( xTimerListsWereSwitched == pdFALSE )
{
/* The tick count has not overflowed, has the timer expired? */
if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) )
{
( void ) xTaskResumeAll();
prvProcessExpiredTimer( xNextExpireTime, xTimeNow );
}
else
{
/* The tick count has not overflowed, and the next expire
* time has not been reached yet. This task should therefore
* block to wait for the next expire time or a command to be
* received - whichever comes first. The following line cannot
* be reached unless xNextExpireTime > xTimeNow, except in the
* case when the current timer list is empty. */
if( xListWasEmpty != pdFALSE )
{
/* The current timer list is empty - is the overflow list
* also empty? */
xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList );
}
vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty );
if( xTaskResumeAll() == pdFALSE )
{
/* Yield to wait for either a command to arrive, or the
* block time to expire. If a command arrived between the
* critical section being exited and this yield then the yield
* will not cause the task to block. */
taskYIELD_WITHIN_API();
}
else
{
mtCOVERAGE_TEST_MARKER();
}
}
}
else
{
( void ) xTaskResumeAll();
}
}
}
timers.c, lines 780–839 · FreeRTOS V11.3.3 · MIT license
At tick 0 no timer is active yet (the start command has not been processed), so the task waits
for a command with no time limit. But a command is already waiting, so
vQueueWaitForMessageRestricted() does not block, and the loop goes on to
prvProcessReceivedCommands().
Processing a command
static void prvProcessReceivedCommands( void )
{
DaemonTaskMessage_t xMessage = { 0 };
Timer_t * pxTimer;
BaseType_t xTimerListsWereSwitched;
TickType_t xTimeNow;
while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL )
{
#if ( INCLUDE_xTimerPendFunctionCall == 1 )
{
/* Negative commands are pended function calls rather than timer
* commands. */
if( xMessage.xMessageID < ( BaseType_t ) 0 )
{
const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters );
/* The timer uses the xCallbackParameters member to request a
* callback be executed. Check the callback is not NULL. */
configASSERT( pxCallback );
/* Call the function. */
pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 );
}
else
{
mtCOVERAGE_TEST_MARKER();
}
}
#endif /* INCLUDE_xTimerPendFunctionCall */
/* Commands that are positive are timer commands rather than pended
* function calls. */
if( xMessage.xMessageID >= ( BaseType_t ) 0 )
{
/* The messages uses the xTimerParameters member to work on a
* software timer. */
pxTimer = xMessage.u.xTimerParameters.pxTimer;
if( pxTimer != NULL )
{
if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE )
{
/* The timer is in a list, remove it. */
( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
}
else
{
mtCOVERAGE_TEST_MARKER();
}
traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue );
/* In this case the xTimerListsWereSwitched parameter is not used, but
* it must be present in the function call. prvSampleTimeNow() must be
* called after the message is received from xTimerQueue so there is no
* possibility of a higher priority task adding a message to the message
* queue with a time that is ahead of the timer daemon task (because it
* pre-empted the timer daemon task after the xTimeNow value was set). */
xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );
switch( xMessage.xMessageID )
{
case tmrCOMMAND_START:
case tmrCOMMAND_START_FROM_ISR:
case tmrCOMMAND_RESET:
case tmrCOMMAND_RESET_FROM_ISR:
/* Start or restart a timer. */
pxTimer->ucStatus |= ( uint8_t ) tmrSTATUS_IS_ACTIVE;
if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) != pdFALSE )
{
/* The timer expired before it was added to the active
* timer list. Process it now. */
if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0U )
{
prvReloadTimer( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow );
}
else
{
pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE );
}
/* Call the timer callback. */
traceTIMER_EXPIRED( pxTimer );
pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
}
else
{
mtCOVERAGE_TEST_MARKER();
}
break;
case tmrCOMMAND_STOP:
case tmrCOMMAND_STOP_FROM_ISR:
/* The timer has already been removed from the active list. */
pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE );
break;
case tmrCOMMAND_CHANGE_PERIOD:
case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR:
pxTimer->ucStatus |= ( uint8_t ) tmrSTATUS_IS_ACTIVE;
pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue;
configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) );
/* The new period does not really have a reference, and can
* be longer or shorter than the old one. The command time is
* therefore set to the current time, and as the period cannot
* be zero the next expiry time can only be in the future,
* meaning (unlike for the xTimerStart() case above) there is
* no fail case that needs to be handled here. */
( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow );
break;
case tmrCOMMAND_DELETE:
#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
{
/* The timer has already been removed from the active list,
* just free up the memory if the memory was dynamically
* allocated. */
if( ( pxTimer->ucStatus & tmrSTATUS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) 0 )
{
vPortFree( pxTimer );
}
else
{
pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE );
}
}
#else /* if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) */
{
/* If dynamic allocation is not enabled, the memory
* could not have been dynamically allocated. So there is
* no need to free the memory - just mark the timer as
* "not active". */
pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE );
}
#endif /* configSUPPORT_DYNAMIC_ALLOCATION */
break;
default:
/* Don't expect to get here. */
break;
}
}
else
{
mtCOVERAGE_TEST_MARKER();
}
}
}
}
timers.c, lines 936–1088 · FreeRTOS V11.3.3 · MIT license
The loop takes commands from the queue without waiting until it is empty. For start(Blink, 0)
it takes Blink out of any list it is in, marks it active, and calls
prvInsertTimerInActiveList() with the expiry 0 + 4:
static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer,
const TickType_t xNextExpiryTime,
const TickType_t xTimeNow,
const TickType_t xCommandTime )
{
BaseType_t xProcessTimerNow = pdFALSE;
listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime );
listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );
if( xNextExpiryTime <= xTimeNow )
{
/* Has the expiry time elapsed between the command to start/reset a
* timer was issued, and the time the command was processed? */
if( ( ( TickType_t ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks )
{
/* The time between a command being issued and the command being
* processed actually exceeds the timers period. */
xProcessTimerNow = pdTRUE;
}
else
{
vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) );
}
}
else
{
if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) )
{
/* If, since the command was issued, the tick count has overflowed
* but the expiry time has not, then the timer must have already passed
* its expiry time and should be processed immediately. */
xProcessTimerNow = pdTRUE;
}
else
{
vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );
}
}
return xProcessTimerNow;
}
timers.c, lines 892–933 · FreeRTOS V11.3.3 · MIT license
Tick 4 is ahead, so Blink goes into pxCurrentTimerList. The function returns pdTRUE only
when the expiry has already passed, which happens when the command waited in the queue for a
whole period; the timer is then processed at once.
Back at the top of the loop, prvGetNextExpireTime() now finds Blink due at tick 4.
prvProcessTimerOrBlockTask() calls vQueueWaitForMessageRestricted() with a block time of 4.
That puts the task in the queue’s xTasksWaitingToReceive list and in the delayed list until
tick 4: it wakes either when a command arrives or when the timer is due, whichever comes first.
The task card shows it blocked on xTimerQueue.
An expiry
At tick 4 the tick takes the timer task out of the delayed list, and it is the most
urgent task, so it runs. This time prvProcessTimerOrBlockTask() finds the expiry time reached and
calls prvProcessExpiredTimer():
static void prvProcessExpiredTimer( const TickType_t xNextExpireTime,
const TickType_t xTimeNow )
{
/* MISRA Ref 11.5.3 [Void pointer assignment] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
/* coverity[misra_c_2012_rule_11_5_violation] */
Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList );
/* Remove the timer from the list of active timers. A check has already
* been performed to ensure the list is not empty. */
( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
/* If the timer is an auto-reload timer then calculate the next
* expiry time and re-insert the timer in the list of active timers. */
if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0U )
{
prvReloadTimer( pxTimer, xNextExpireTime, xTimeNow );
}
else
{
pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE );
}
/* Call the timer callback. */
traceTIMER_EXPIRED( pxTimer );
pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
}
timers.c, lines 716–743 · FreeRTOS V11.3.3 · MIT license
Blink reloads, so prvReloadTimer() puts it back first, due one period after the expiry it is
processing (4 + 4 = 8): counted from when it was due, so the period does not drift even if the
task ran late. Only then is the callback called, in the timer task’s own context, at its priority.
vBlinkCallback() gives S, which readies Handler, and the loop goes round to wait until tick 8.
If the task ran so late that the next expiry has passed too, prvReloadTimer() calls the callback
once for each missed expiry before it finds one in the future. Set Timer task urgency to 2 and
see the tick-8 callback run at tick 11, with the next expiry still at 12.
A stop
At tick 13 Keys calls xTimerStop(). The command stop(Blink) goes
into the queue, which wakes the timer task from its wait. It is more urgent than Keys, so it runs
before xQueueSend() even returns to Keys. prvProcessReceivedCommands() takes Blink out of
the list and clears tmrSTATUS_IS_ACTIVE; there is nothing more to do for a stop. With no timer
active, the task waits for a command with no time limit, in xSuspendedTaskList.
What it costs
A timer costs a Timer_t and nothing else: one task and one queue serve every timer. The price is
that everything is serialised through that task. A long callback delays every other callback and
every command, and a timer task below a busy task delays them all. An interrupt can also send
commands, through xTimerStartFromISR() and friends, and so does
xEventGroupSetBitsFromISR(), which hands its work to this task.