</>EmbeddedInterview

What is the difference between vTaskDelay and vTaskDelayUntil?

MediumRTOS & Real-Time Systems

Short answer: vTaskDelay(n) blocks the task for n ticks counted from the moment it is called, so if the task's own work takes variable time, its period drifts. vTaskDelayUntil(&last_wake, period) (or xTaskDelayUntil) blocks until an absolute time last_wake + period and then updates last_wake, giving a fixed-frequency loop with no drift.

/* drifts: period = 10 ms + execution time (variable) */
for (;;) {
    control_step();
    vTaskDelay(pdMS_TO_TICKS(10));
}

/* fixed 10 ms period, independent of execution time */
TickType_t last = xTaskGetTickCount();
for (;;) {
    vTaskDelayUntil(&last, pdMS_TO_TICKS(10));
    control_step();
}

Timeline (control step takes 2–4 ms)

vTaskDelay:       run(3) wait(10) run(2) wait(10) run(4) wait(10)  → wake times 13, 25, 39 ...
vTaskDelayUntil:  wake at 10, 20, 30, 40 ... regardless of run time

Details

  • If the task overruns (work takes longer than the period), vTaskDelayUntil returns immediately and the task runs late; xTaskDelayUntil returns pdFALSE in that case, so you can detect overruns.
  • Neither gives better than ±1 tick precision, and higher-priority tasks or interrupts can delay the actual start (jitter). For tight timing (e.g. a 1 kHz control loop with low jitter), trigger the task from a hardware timer interrupt with a notification.
  • vTaskDelay(0) just yields.

Zephyr equivalents: k_sleep() / k_msleep() (relative) and k_sleep(K_TIMEOUT_ABS_MS(...)) or periodic k_timer + k_timer_status_sync() for absolute timing.