Skip to content
systemcoding.dev
RTOS

Change a Software Timer Period at Runtime With xTimerChangePeriod

Change a running FreeRTOS timer's period with xTimerChangePeriod: what happens to the countdown, the block time, ISR use and a retry backoff example.

7 min read
Summarize in AI
Flat illustration of a program timeline interrupted by an interrupt service routine, with the C, RISC-V and Rust logos.

A timer created with a period of 500 ms keeps that period forever, unless you change it. Real firmware needs to: a retry interval that grows after each failure, a sampling rate the user can set, a blink that speeds up as a battery drains. FreeRTOS gives you xTimerChangePeriod() for this. It is one call, and it has three behaviors that surprise people: it restarts the timer from now, it starts a stopped timer, and it can fail without telling you unless you look at the return value. This post covers all three on FreeRTOS kernel V11.1.0, then builds an exponential-backoff retry timer as a worked example. Creating timers is covered in the xTimerCreate post.

The call

c
BaseType_t xTimerChangePeriod(TimerHandle_t xTimer,
                              TickType_t    xNewPeriod,
                              TickType_t    xTicksToWait);

xNewPeriod is in ticks and must be above zero. xTicksToWait is how long the caller will wait if the timer command queue is full. The function returns pdPASS if the command was queued, and pdFAIL if the queue stayed full for the whole wait. A pdPASS means the command was queued, not yet applied: the timer service task applies it a moment later.

What it does to the countdown

Three rules cover every case:

The timer wasAfter xTimerChangePeriod()
RunningThe new period starts counting from the moment of the call. The old countdown is discarded
Stopped or dormantThe timer starts, with the new period
A fired one-shotThe timer starts again, with the new period

The first rule is the one to design around. If a 400-tick timer started at tick 0 is changed to a 1,000-tick period at tick 250, it expires at 1,250, not at 1,000 and not at 400. The time already elapsed is not credited.

retune.cc
#include <stdio.h>
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"

static TimerHandle_t s_poll;

static void poll_cb(TimerHandle_t t)
{
    (void)t;
    printf("[%lu] poll\n", (unsigned long)xTaskGetTickCount());
}

static void user_task(void *arg)
{
    (void)arg;
    vTaskDelay(pdMS_TO_TICKS(250));
    printf("[%lu] user changes the rate to 1000 ms\n", (unsigned long)xTaskGetTickCount());
    if (xTimerChangePeriod(s_poll, pdMS_TO_TICKS(1000), pdMS_TO_TICKS(10)) != pdPASS) {
        printf("change failed\n");
    }
    vTaskDelete(NULL);
}

void retune_demo(void)
{
    s_poll = xTimerCreate("poll", pdMS_TO_TICKS(100), pdTRUE, NULL, poll_cb);
    xTimerStart(s_poll, 0);
    xTaskCreate(user_task, "user", 256, NULL, 2, NULL);
}
Text
[100] poll
[200] poll
[250] user changes the rate to 1000 ms
[1250] poll
[2250] poll

The timer fired at 100 and 200 with its old period. The change at 250 threw away the 50 ticks already counted toward the 300 expiry, and the next callback came a full 1,000 ticks later. If a short gap in polling is not acceptable, call the callback yourself once after the change, or pick a new period from the time left.

Keeping the phase

Sometimes the new period should take effect at the next scheduled expiry, not immediately. The timer has no call for that, but you can do it from the callback, which runs exactly at the old expiry:

phase.cc
static volatile TickType_t s_pendingPeriod;       /* 0 means no change requested */

static void poll_cb2(TimerHandle_t t)
{
    printf("[%lu] poll\n", (unsigned long)xTaskGetTickCount());

    TickType_t next = s_pendingPeriod;
    if (next != 0) {
        s_pendingPeriod = 0;
        xTimerChangePeriod(t, next, 0);            /* block time 0: never wait in a callback */
    }
}

void request_new_period(TickType_t period)
{
    s_pendingPeriod = period;                      /* applied at the next expiry */
}

The request is stored, and the callback applies it right after it runs, so the transition happens on a tick the old schedule already had. With a request for 1,000 ticks made at tick 250:

Text
[100] poll
[200] poll
[300] poll
[1300] poll

The new period begins at 300, the old expiry, and the next callback is 1,000 ticks later. The xTimerChangePeriod() inside the callback uses a block time of 0, which is required: a callback must never wait.

From an interrupt

xTimerChangePeriodFromISR() has the same effect and takes a woken pointer:

isr_change.cc
void ENCODER_IRQHandler(void)
{
    BaseType_t woken = pdFALSE;
    TickType_t period = encoder_to_period_ticks(read_encoder());

    clear_encoder_interrupt();
    xTimerChangePeriodFromISR(s_poll, period, &woken);
    portYIELD_FROM_ISR(woken);
}

It returns pdPASS or pdFAIL, like the task version. A rotary encoder that fires many times a second can flood the command queue with period changes; keep the latest value in a variable and apply it from a task at a sensible rate, if the rate of change is high.

A worked example: exponential backoff

A device tries to reconnect to a server. After each failure it should wait longer before the next try: 1 s, 2 s, 4 s, up to a cap of 32 s. After a success it goes back to 1 s. A one-shot timer with a changing period is a natural fit.

backoff.cc
#include <stdio.h>
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"

#define BACKOFF_MIN_MS   1000u
#define BACKOFF_MAX_MS   32000u

static TimerHandle_t s_retryTimer;
static uint32_t      s_backoffMs = BACKOFF_MIN_MS;

static void retry_cb(TimerHandle_t t)
{
    (void)t;
    if (connect_to_server() == 0) {
        printf("[%lu] connected\n", (unsigned long)xTaskGetTickCount());
        s_backoffMs = BACKOFF_MIN_MS;                  /* success: reset */
        return;
    }

    printf("[%lu] connect failed, next try in %lu ms\n",
           (unsigned long)xTaskGetTickCount(), (unsigned long)s_backoffMs);

    xTimerChangePeriod(t, pdMS_TO_TICKS(s_backoffMs), 0);   /* re-arms the one-shot */

    if (s_backoffMs < BACKOFF_MAX_MS) {
        s_backoffMs *= 2u;
    }
}

void retry_start(void)
{
    s_retryTimer = xTimerCreate("retry", pdMS_TO_TICKS(BACKOFF_MIN_MS), pdFALSE, NULL, retry_cb);
    configASSERT(s_retryTimer != NULL);
    xTimerStart(s_retryTimer, 0);
}

A one-shot timer stops after it fires, so xTimerChangePeriod() inside the callback both sets the new period and starts the timer again, which is the third row of the table. With a server that refuses the first three attempts and accepts the fourth:

Text
[1000] connect failed, next try in 1000 ms
[2000] connect failed, next try in 2000 ms
[4000] connect failed, next try in 4000 ms
[8000] connected

Read the numbers carefully. The first attempt fails at tick 1,000 and the code re-arms with s_backoffMs, which is still 1,000, then doubles it for next time. So the first delay is 1,000, the second 2,000 and the third 4,000, and the attempts happen at 1,000, 2,000, 4,000 and 8,000. The doubling comes after the use, which is a common off-by-one in backoff code. If you want the first retry to wait 2,000, double before the call.

The doubling stops at the cap, and the reset after success goes back to the minimum. There is no task and no stack: the whole retry machinery is one timer and eight lines of callback.

Adding random jitter to the period is wise in a fleet of devices that all lose the server at once, so they do not retry in lockstep. Compute s_backoffMs + (rand() % 250), from a source of randomness appropriate to your part.

Mistakes to avoid

Assuming the elapsed time counts. The change restarts the countdown. If you need to preserve the remaining time, read xTimerGetExpiryTime() before the call and compute the new period from it.

A period of zero. It is invalid. If you compute a period from a variable, guard against zero, and clamp very small values to at least one tick.

Ignoring the return value. A full command queue drops the change, and the timer keeps its old period. Check pdPASS where it matters.

Using a nonzero block time in a callback. It can freeze the timer task. Pass 0.

Forgetting that the change is queued. xTimerGetPeriod() immediately after the call returns the old period until the timer task has processed the command. If you need the new value, keep your own copy.

query.cc
xTimerChangePeriod(s_poll, pdMS_TO_TICKS(1000), 0);
printf("period now %lu\n", (unsigned long)xTimerGetPeriod(s_poll));

If the timer task runs at a higher priority than the calling task, it processes the command before the call returns, and the line prints 1,000. If it runs at a lower priority, it prints the old value, the previous period. The result depends on priorities, which is why the code should not depend on it.

Choosing the new period

Where the new period comes from deserves a moment. A period the user sets should be validated before it reaches the timer: reject zero, and clamp it to a range that the system can sustain. A period of one tick on a 1,000 Hz system asks the timer task to run a callback a thousand times a second, which may starve other work, so choose a floor from the cost of the callback. Convert the user's value in milliseconds with pdMS_TO_TICKS() and check the result is at least one tick, or the conversion truncates a small value to zero at low tick rates.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.