Use the FreeRTOS Idle Hook to Run Background Work
Run low-priority background work in vApplicationIdleHook: enable it, keep it short and non-blocking, work in slices, and know when a task is better.

Every FreeRTOS system has a task that runs when nothing else can: the idle task. It has the lowest priority, so it only gets the processor when every other task is blocked. The kernel lets you attach a function to it, the idle hook, which runs on each pass of the idle loop. That makes the hook a place for work that has no deadline and should never delay anything: a checksum pass over flash, a statistics counter, a tidy-up of a data structure. This post enables the hook on FreeRTOS kernel V11.1.0, writes a background CRC checker that works in small slices, shows the three rules the hook must obey, and says when a low-priority task or a software timer is the better tool. The full context is in the guide to software timers and tickless idle.
What the idle task does
vTaskStartScheduler() creates the idle task automatically, at priority tskIDLE_PRIORITY, which is 0. It runs a loop that does two things each time round:
It frees the memory of tasks that were deleted, since a task cannot free its own stack while still running.
If you enabled it, it calls
vApplicationIdleHook().
Because the idle task runs only when all other tasks are blocked, anything in the hook automatically yields to everything else. The moment any task becomes ready, the scheduler preempts the idle task, including in the middle of your hook.
Turn it on
#define configUSE_IDLE_HOOK 1Then define the function once in your application. The name and signature are fixed, and a missing definition is a link error:
#include "FreeRTOS.h"
#include "task.h"
static volatile uint32_t s_idlePasses;
void vApplicationIdleHook(void)
{
s_idlePasses++;
}That already does something useful. The counter rises whenever the system has spare time, so reading it periodically gives a crude idea of how busy the system is: a counter that barely moves means no idle time.
The three rules
Never block. The hook must not call vTaskDelay(), wait on a queue or a semaphore with a timeout, or do anything else that puts the idle task in the Blocked state. The idle task must always be ready to run, because the scheduler needs something to run when everything else is blocked. If it blocked, the scheduler would have nothing to schedule.
Return regularly. The idle loop frees deleted tasks' memory between hook calls. A hook that loops for a long time delays that cleanup, and memory from deleted tasks is not reclaimed in the meantime. Do a small slice of work and return.
Keep it short. Work in the hook delays the idle task's entry into a low-power sleep, if you use one, and it delays the next check of the kernel's housekeeping. Interrupts still run, and any ready task preempts the hook, but a long hook is wasted effort if the work could be done elsewhere.
A background checker that works in slices
A device wants to verify its flash contents continuously, in case of corruption, without disturbing the real-time tasks. A full CRC of 256 KiB in one go would take milliseconds, which is too long for a hook. So the hook checks one 256-byte block per pass and remembers where it was.
#include <stdio.h>
#include <stdint.h>
#include "FreeRTOS.h"
#include "task.h"
#define FLASH_BASE_ADDR 0x08000000u
#define FLASH_SIZE_BYTES (256u * 1024u)
#define SLICE_BYTES 256u
extern uint32_t crc32_update(uint32_t crc, const uint8_t *data, uint32_t len);
static uint32_t s_offset;
static uint32_t s_crc = 0xFFFFFFFFu;
static volatile uint32_t s_lastGood;
static volatile uint32_t s_passes;
void vApplicationIdleHook(void)
{
const uint8_t *p = (const uint8_t *)(FLASH_BASE_ADDR + s_offset);
s_crc = crc32_update(s_crc, p, SLICE_BYTES);
s_offset += SLICE_BYTES;
if (s_offset >= FLASH_SIZE_BYTES) {
s_lastGood = ~s_crc; /* finished a full pass */
s_passes++;
s_offset = 0;
s_crc = 0xFFFFFFFFu;
}
}
uint32_t scrub_result(uint32_t *passes)
{
*passes = s_passes;
return s_lastGood;
}Each call handles a bounded amount of work, 256 bytes, and returns, so the idle task keeps coming back to free memory and check for sleep. A reporting task reads the result:
static void report_task(void *arg)
{
(void)arg;
for (;;) {
uint32_t passes;
uint32_t crc = scrub_result(&passes);
printf("[%lu] flash scrub: %lu full passes, last crc 0x%08lX\n",
(unsigned long)xTaskGetTickCount(),
(unsigned long)passes, (unsigned long)crc);
vTaskDelay(pdMS_TO_TICKS(5000));
}
}[5000] flash scrub: 3 full passes, last crc 0x7A31C2E9The number of passes and the CRC value are examples; your pass rate depends on how much idle time the system has, and the CRC depends on your image. If the CRC of a later pass differs from the first, the flash content changed: that is the corruption check. Variables shared between the hook and a task are volatile, and a 32-bit read or write on a Cortex-M is a single instruction, so no lock is needed for these simple values; a structure would need a critical section.
Do not combine it carelessly with sleep
A common instinct is to put __WFI() in the hook to save power. It works, and it is a fine first step: the processor sleeps until the next interrupt, which at worst is the next tick. But if you also enable tickless idle, the kernel itself stops the tick and sleeps from the idle task, after the hook returns. A __WFI() in the hook then sleeps first, wakes on the tick, and only then does the kernel's tickless logic run, defeating the purpose. With tickless idle on, leave the sleeping to the kernel and use the hook only for work.
void vApplicationIdleHook(void)
{
#if (configUSE_TICKLESS_IDLE == 0)
__WFI(); /* wake on the next tick or interrupt */
#endif
background_slice();
}The #if makes the choice explicit. With tickless idle off, the hook sleeps. With it on, the hook only works.
Idle hook, task or timer
The hook is not the only place for background work, and it is the least flexible. Compare:
| Need | Best fit | Why |
|---|---|---|
| A little work whenever the system is free, no stack to spare | Idle hook | Runs on the idle task's stack, no extra task |
| Background work that must block, wait or use RTOS calls | Low-priority task | Can block, has its own stack |
| Work at a regular period | Software timer, or a task with vTaskDelayUntil() | Has a schedule |
| Work that should happen even when the system is never idle | A low-priority task at priority 1 | The hook never runs if something is always ready |
| Work with a deadline | A task at a suitable priority | The hook has none |
The last two rows matter. The hook runs only when every other task is blocked. A system that is never fully idle never runs the hook, so background work placed there starves silently. A low-priority task at priority 1, in contrast, gets the processor whenever higher-priority tasks block, even if the idle task never runs, because it competes with the idle task and wins.
A second limit is that the hook cannot use most of the kernel API, because it cannot block. It can call non-blocking functions such as xQueueSend() with a zero timeout, or xTaskNotifyGive(), but anything that waits is out. A background job that needs a mutex belongs in a task.
Using the hook to feed a watchdog
A neat use of the hook is feeding an independent watchdog, but only when the system is healthy. If the hook runs, every other task is blocked, which means none is stuck in a long loop, so the system is making progress. If a task spins forever, the hook never runs, the watchdog is not fed and the device resets:
void vApplicationIdleHook(void)
{
IWDG->KR = 0xAAAA; /* reload the independent watchdog */
}This catches a task that runs away, but not a task that is blocked forever waiting for something, because the idle task still runs in that case. Combine it with per-task heartbeats if you need to catch both, as the watchdog-style timeout post shows for software supervision.


