Create One-Shot and Auto-Reload Timers With xTimerCreate
Create FreeRTOS software timers with xTimerCreate: the five arguments, one-shot versus auto-reload, why a new timer is dormant and how to restart a one-shot.

A software timer is the cheapest way to say "run this function in 200 milliseconds" in FreeRTOS. You do not create a task, and you do not need a hardware timer peripheral. You create a timer, start it, and the kernel calls your function when the time is up. This post teaches xTimerCreate() from the first line on FreeRTOS kernel V11.1.0: its five arguments, the difference between a one-shot and an auto-reload timer, the surprise that a new timer does nothing until you start it, and how to run a one-shot again. The machinery behind it is in the timer service task post, and the whole subject in the guide to software timers and tickless idle.
Switch the feature on
Software timers are off by default. Add this to FreeRTOSConfig.h, and make sure timers.c is part of your build:
#define configUSE_TIMERS 1
#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 2 )
#define configTIMER_QUEUE_LENGTH 10
#define configTIMER_TASK_STACK_DEPTH ( configMINIMAL_STACK_SIZE * 2 )With configUSE_TIMERS set to 1, vTaskStartScheduler() creates a task called the timer service task. It runs every timer callback. The other three settings give it a priority, a command queue length and a stack size in words.
The five arguments
TimerHandle_t xTimerCreate(const char * const pcTimerName,
const TickType_t xTimerPeriodInTicks,
const BaseType_t xAutoReload,
void * const pvTimerID,
TimerCallbackFunction_t pxCallbackFunction);| Argument | Meaning |
|---|---|
pcTimerName | A text name, used only by debuggers. Keep it short |
xTimerPeriodInTicks | The period in ticks. It must be greater than zero. Use pdMS_TO_TICKS() to convert milliseconds |
xAutoReload | pdTRUE for a timer that repeats, pdFALSE for one that fires once |
pvTimerID | A void * you can read back in the callback with pvTimerGetTimerID(). Pass NULL if you do not need it |
pxCallbackFunction | The function to run when the period expires |
The callback must have exactly this shape, taking the timer handle and returning nothing:
void my_callback(TimerHandle_t xTimer);The function returns a TimerHandle_t, or NULL if there was not enough heap for the timer's control block. Always check it. The reload parameter is named uxAutoReload in V11 and xAutoReload in earlier versions, but passing pdTRUE or pdFALSE works in every version.
One-shot and auto-reload side by side
#include <stdio.h>
#include "FreeRTOS.h"
#include "timers.h"
#include "task.h"
static void tick_callback(TimerHandle_t xTimer)
{
(void)xTimer;
printf("[%lu] auto-reload fired\n", (unsigned long)xTaskGetTickCount());
}
static void alarm_callback(TimerHandle_t xTimer)
{
(void)xTimer;
printf("[%lu] one-shot fired\n", (unsigned long)xTaskGetTickCount());
}
int main(void)
{
TimerHandle_t tick = xTimerCreate("tick", pdMS_TO_TICKS(300), pdTRUE, NULL, tick_callback);
TimerHandle_t alarm = xTimerCreate("alarm", pdMS_TO_TICKS(700), pdFALSE, NULL, alarm_callback);
configASSERT(tick != NULL);
configASSERT(alarm != NULL);
xTimerStart(tick, 0);
xTimerStart(alarm, 0);
vTaskStartScheduler();
for (;;) { }
}With configTICK_RATE_HZ at 1,000, so one tick is one millisecond:
[300] auto-reload fired
[600] auto-reload fired
[700] one-shot fired
[900] auto-reload fired
[1200] auto-reload firedThe auto-reload timer keeps firing every 300 ms. The one-shot fired at 700 ms and then stayed silent. After a one-shot fires, the timer still exists, but it is stopped, and you can start it again.
The timer is dormant until you start it
xTimerCreate() makes the timer and does nothing else. This is the mistake behind most "my timer never fires" questions. The start call is separate:
BaseType_t xTimerStart(TimerHandle_t xTimer, TickType_t xTicksToWait);The second argument is how long to wait if the timer command queue is full. Called before vTaskStartScheduler(), it has no effect on timing: the clock starts when the scheduler does. After the scheduler is running, a block time of 0 means "do not wait", and a nonzero value lets the caller wait for queue space. Inside a timer callback, always pass 0: a callback that waits can freeze the timer task.
The return value is pdPASS if the start command was queued and pdFAIL if it was not. Check it where it matters:
if (xTimerStart(alarm, pdMS_TO_TICKS(10)) != pdPASS) {
printf("could not queue the start command\n");
}You can ask whether a timer is running with xTimerIsTimerActive(), which returns pdFALSE for a timer that is dormant, stopped, or a one-shot that has fired:
static void show_state(TimerHandle_t t)
{
printf("%s is %s\n", pcTimerGetName(t),
xTimerIsTimerActive(t) != pdFALSE ? "active" : "not active");
}alarm is not activeRunning a one-shot again
A one-shot timer is a reusable countdown. To use it again, start it again:
static TimerHandle_t s_backlight;
static void backlight_off(TimerHandle_t t)
{
(void)t;
gpio_backlight(0);
printf("[%lu] backlight off\n", (unsigned long)xTaskGetTickCount());
}
void backlight_init(void)
{
s_backlight = xTimerCreate("light", pdMS_TO_TICKS(5000), pdFALSE, NULL, backlight_off);
configASSERT(s_backlight != NULL);
}
void backlight_touch(void) /* call this on every user input */
{
gpio_backlight(1);
xTimerReset(s_backlight, 0); /* start it, or restart the 5 s from now */
}xTimerReset() is the right call here, not xTimerStart(). It starts a dormant timer and restarts a running one from the current time. A screen that stays lit for 5 seconds after the last touch is the perfect use: every touch pushes the deadline out. If the user touches at 0 s and 3 s and then stops, the backlight turns off at 8 s:
[8000] backlight offxTimerStart() on an already-running timer does nothing useful: it leaves the expiry as it was. When you want "restart the countdown", use reset.
Changing the mode later
You can change a timer between one-shot and auto-reload after creation with vTimerSetReloadMode(), which takes the handle and pdTRUE or pdFALSE:
vTimerSetReloadMode(s_backlight, pdTRUE); /* now it repeats */It is rarely needed. If you find yourself switching modes at run time, a pair of timers or a state flag in the callback is usually clearer.
Mistakes to avoid
Forgetting to start. The timer exists and is dormant. Add the start call and check the return value.
A period of zero. The period must be positive. pdMS_TO_TICKS(1) at a tick rate below 1,000 Hz truncates to 0 and the creation asserts. If a short period reads as zero ticks, raise configTICK_RATE_HZ or lengthen the period.
A blocking callback. Callbacks run in the timer service task, which is shared. A vTaskDelay() inside one stops all timers. Do the quick thing in the callback, or notify a task.
**A local TimerHandle_t that goes out of scope.** The handle is just a pointer. If you lose it, you cannot stop or delete the timer. Store handles in a static or global variable if you need them later.
Creating timers from an interrupt. xTimerCreate() allocates memory and is for tasks only. Create timers at start-up and use the FromISR start, stop and reset calls in interrupts.
Expecting exact times. A timer fires on a tick boundary, and the callback runs when the timer service task gets the processor. It is accurate to about a tick, and later if a higher-priority task is busy.
Deleting a timer
xTimerDelete(t, block) removes a timer and frees its memory if it was created dynamically. Do not use the handle afterwards. Many designs never delete timers, creating them once at start-up and starting and stopping them as needed, which avoids heap fragmentation.
xTimerDelete(s_backlight, pdMS_TO_TICKS(10));
s_backlight = NULL; /* do not keep a stale handle */Stopping and cleaning up
A timer you start should have a matching way to stop, even if you never use it in production. xTimerStop(t, 0) halts a timer and leaves it ready to start again, and it is the right call when a feature turns off, for example when a device leaves a mode that needed the blink. A stopped timer costs nothing but its control block, and restarting it is a single call.
For a timer you will never use again, xTimerDelete() frees it. The command is queued, so the handle stays valid until the timer service task processes it, and you must not use the handle after the call returns. A common pattern is to set the stored handle to NULL immediately after deleting, so a later stop or start in the same module sees NULL and does nothing, instead of passing a stale handle to the kernel.
Finally, remember that a one-shot timer needs no cleanup after it fires: it is stopped, not deleted, and the same handle works for the next countdown.


