Run Periodic Code With Zephyr k_timer
Run code every N milliseconds in Zephyr with k_timer, including one-shot and periodic modes, the expiry callback rules and how to wake a thread from it.

Many embedded jobs happen on a schedule: read a sensor every second, blink an LED twice a second, send a heartbeat every thirty seconds. The first idea is a loop that sleeps, and that works until you need several schedules at once, or a precise period that does not drift by the time the work takes. Zephyr provides kernel timers, k_timer, for exactly this. A timer is an object that calls a function when it expires, once or repeatedly, without a thread of its own. This post shows how to define, start and stop one in Zephyr 4.2, what the callback may and may not do, and two ways to connect a timer to a thread that does real work. It is the third rung of the threads ladder and uses the ideas from the guide to threads.
Define and start a timer
A timer needs a name, an expiry function and an optional stop function. The macro K_TIMER_DEFINE creates it at build time:
#include <zephyr/kernel.h>
static void heartbeat(struct k_timer *timer)
{
printk("beat at %lld ms\n", k_uptime_get());
}
K_TIMER_DEFINE(heartbeat_timer, heartbeat, NULL);
int main(void)
{
k_timer_start(&heartbeat_timer, K_SECONDS(1), K_SECONDS(1));
k_sleep(K_SECONDS(5));
k_timer_stop(&heartbeat_timer);
printk("stopped\n");
return 0;
}CONFIG_PRINTK=yK_TIMER_DEFINE(name, expiry_fn, stop_fn) defines the timer, with NULL for the stop function when you do not need one. k_timer_start(timer, duration, period) arms it. The first expiry occurs after duration, and later ones every period. Here both are one second, so the callback runs once a second. k_timer_stop disarms it. The output is:
*** Booting Zephyr OS build v4.2.0 ***
beat at 1000 ms
beat at 2000 ms
beat at 3000 ms
beat at 4000 ms
beat at 5000 ms
stoppedThe fifth beat and the stop happen at nearly the same moment, so whether the fifth line prints before "stopped" depends on which expires first. The timestamps are the kernel's uptime in milliseconds, and they will be offset by the time the program took to start. The reference is the timers documentation.
One-shot, periodic and delayed start
The two time arguments express three behaviors:
duration | period | Behavior |
|---|---|---|
K_MSEC(500) | K_NO_WAIT | One-shot: fires once after 500 ms |
K_MSEC(500) | K_MSEC(500) | Periodic: first after 500 ms, then every 500 ms |
K_MSEC(100) | K_SECONDS(1) | First after 100 ms, then every second |
K_NO_WAIT | K_SECONDS(1) | First immediately, then every second |
A period of K_NO_WAIT or K_FOREVER makes the timer one-shot. Restarting a running timer with k_timer_start resets it with the new values.
A key property of periodic timers: the period is measured from the previous expiry, not from the end of the callback. A callback that takes 10 ms in a 1000 ms period does not push the next one to 1010 ms. That is the advantage over a while (1) { work(); k_msleep(1000); } loop, which drifts by the duration of the work every iteration. The kernel timer does not drift on its own, though if the system is too busy to handle expiries, they are processed late and the timer's status count increases to record missed periods.
What the callback runs in
The expiry function runs in the system clock interrupt context, or in a thread-like context after it, depending on the kernel configuration, but it must be treated as an interrupt handler. That has firm consequences:
No blocking. Do not call
k_msleep, take a mutex, or callk_sem_takewith a timeout. Doing so triggers an assertion or hangs the kernel tick.Keep it short. The callback delays all other timer expiries and scheduling while it runs.
Use only interrupt-safe calls.
k_sem_give,k_msgq_putwithK_NO_WAIT,k_work_submit,k_event_post, atomic operations and GPIO writes are all fine.
If the work is longer than a few lines, hand it to a thread. Two patterns do that.
Pattern 1: wake a thread with a semaphore
The callback gives a semaphore, and a thread waits for it:
#include <zephyr/kernel.h>
K_SEM_DEFINE(tick_sem, 0, 1);
static void tick(struct k_timer *timer)
{
k_sem_give(&tick_sem);
}
K_TIMER_DEFINE(tick_timer, tick, NULL);
static void sampler(void *p1, void *p2, void *p3)
{
int n = 0;
while (1) {
k_sem_take(&tick_sem, K_FOREVER);
printk("sample %d (this may take a while)\n", n++);
k_busy_wait(2000);
}
}
K_THREAD_DEFINE(sampler_id, 1024, sampler, NULL, NULL, NULL, 5, 0, 0);
int main(void)
{
k_timer_start(&tick_timer, K_MSEC(100), K_MSEC(100));
return 0;
}The timer fires every 100 ms, and the sampler thread wakes, does its work and waits again. Because the semaphore is binary, if the thread is still busy when the next tick arrives, the give is remembered once, and a second tick during the same period is lost. For a thread that must process every tick, use a counting semaphore with a larger limit, or check the timer's status with k_timer_status_sync.
Pattern 2: submit work to a work queue
The callback submits a work item, and the system work queue runs the handler in a thread:
#include <zephyr/kernel.h>
static void do_sample(struct k_work *work)
{
printk("sampling in a thread\n");
}
K_WORK_DEFINE(sample_work, do_sample);
static void tick(struct k_timer *timer)
{
k_work_submit(&sample_work);
}
K_TIMER_DEFINE(tick_timer, tick, NULL);This avoids defining a thread and a semaphore, and the handler may block briefly. It shares the system work queue with other users, so keep it short. For a periodic job that is only ever done in a work item, delayable work is a closer fit, and the post on k_work_reschedule covers it.
Waiting for a timer from a thread
A thread can wait for a timer instead of registering a callback. k_timer_status_sync blocks until the timer has expired at least once since the last call, and returns the number of expiries it saw:
K_TIMER_DEFINE(pace, NULL, NULL);
static void paced_thread(void *p1, void *p2, void *p3)
{
k_timer_start(&pace, K_MSEC(200), K_MSEC(200));
while (1) {
uint32_t missed = k_timer_status_sync(&pace);
if (missed > 1) {
printk("missed %u periods\n", missed - 1);
}
do_cycle();
}
}Passing NULL as the expiry function creates a timer that only counts. The thread runs a cycle every 200 ms with no drift, and if a cycle runs long, the next k_timer_status_sync returns a count greater than one, which tells you how many periods you missed. This pattern gives a periodic thread with fixed timing and built-in overrun detection, and it is often better than a semaphore handoff.
Passing context to the callback
The callback receives only the timer pointer. To carry data, attach a pointer with k_timer_user_data_set and read it back with k_timer_user_data_get:
struct blinker {
struct k_timer timer;
int pin;
int state;
};
static void blink_cb(struct k_timer *t)
{
struct blinker *b = k_timer_user_data_get(t);
b->state = !b->state;
printk("pin %d -> %d\n", b->pin, b->state);
}
static struct blinker led_a = { .pin = 13 };
void setup(void)
{
k_timer_init(&led_a.timer, blink_cb, NULL);
k_timer_user_data_set(&led_a.timer, &led_a);
k_timer_start(&led_a.timer, K_MSEC(250), K_MSEC(250));
}k_timer_init is the run-time counterpart of K_TIMER_DEFINE. It lets you embed a timer in your own structure, one per instance. Alternatively, use CONTAINER_OF(t, struct blinker, timer) to get the enclosing structure without user data.
Precision and limits
A timer's resolution is one kernel tick, set by CONFIG_SYS_CLOCK_TICKS_PER_SEC. Durations round up to a whole tick. On a board with a 32768 Hz clock and tick rate of 32768, a tick is about 30 microseconds, and on a board with 100 ticks per second it is 10 ms, so check the setting for your board. The timer is as accurate as the hardware clock behind it, which for a crystal-based clock is far better than the tick, and for an internal RC oscillator is much worse.
Timers are cheap, since each is a small structure in a sorted list. Dozens are fine. For very short intervals, such as microsecond waveforms, use a hardware counter peripheral instead.


