Skip to content
systemcoding.dev
RTOS

Schedule Delayed Work With k_work_reschedule

Use struct k_work_delayable with k_work_schedule and k_work_reschedule to run work after a delay, then build a debounce, a timeout and a periodic task.

7 min read
Summarize in AI
Flat illustration of RTOS tasks taking turns on a timeline, with the C, Rust and Espressif logos.

Plain work items run as soon as the queue gets to them. Many jobs need to run later: ignore a button for 50 ms after the first edge, retry a failed transfer after a second, shut a radio down if no packet arrives for ten seconds. Zephyr's delayable work item, struct k_work_delayable, attaches a timer to a work item, so the handler runs on the workqueue after a delay you choose. Two calls schedule it, k_work_schedule and k_work_reschedule, and the difference between them is the whole subject of this post. It shows both in Zephyr 4.2 with a debounce, a timeout and a periodic task. It builds on the system workqueue post.

The delayable work object

A delayable work item wraps a normal work item with a timeout. Define and initialize it like this:

c
#include <zephyr/kernel.h>

static void handler(struct k_work *work)
{
	struct k_work_delayable *dwork = k_work_delayable_from_work(work);

	printk("delayed work ran at %lld ms\n", k_uptime_get());
}

K_WORK_DELAYABLE_DEFINE(my_dwork, handler);

The handler still receives a struct k_work *. To get the delayable structure, call k_work_delayable_from_work(work). If you embed the delayable item in a larger structure, use CONTAINER_OF on the delayable item to reach your data. K_WORK_DELAYABLE_DEFINE(name, handler) defines it at build time. At run time, use k_work_init_delayable(&dwork, handler) once at startup. The reference is the workqueue documentation.

schedule versus reschedule

Both calls take the item and a delay, and both submit it to the system workqueue, or use the _for variants for another queue. The difference is what they do when the item is already waiting for its delay:

CallIf the item is idleIf the item is already scheduled but not yet queued
k_work_schedule(&d, delay)Schedules it after delayDoes nothing. The original deadline stands
k_work_reschedule(&d, delay)Schedules it after delayCancels the pending delay and starts a new one

k_work_schedule keeps the earliest deadline, which makes it right for "make sure this happens within N ms". k_work_reschedule moves the deadline, which makes it right for "do this N ms after the last time something happened". The first is a rate limiter, and the second is a debounce or a timeout.

To see it, call both in a row:

src/main.cc
#include <zephyr/kernel.h>

static void handler(struct k_work *work)
{
	printk("ran at %lld ms\n", k_uptime_get());
}

K_WORK_DELAYABLE_DEFINE(job, handler);

int main(void)
{
	printk("start %lld ms\n", k_uptime_get());

	k_work_schedule(&job, K_MSEC(500));
	k_msleep(200);
	k_work_schedule(&job, K_MSEC(500));
	k_msleep(1000);

	printk("--- reschedule ---\n");
	k_work_reschedule(&job, K_MSEC(500));
	k_msleep(200);
	k_work_reschedule(&job, K_MSEC(500));
	k_msleep(1000);
	return 0;
}
prj.confText
CONFIG_PRINTK=y

With k_work_schedule, the second call at 200 ms is ignored, so the handler runs at about 500 ms. With k_work_reschedule, the second call at 200 ms pushes the deadline out to 700 ms from the start of that section:

Text
*** Booting Zephyr OS build v4.2.0 ***
start 0 ms
ran at 501 ms
--- reschedule ---
ran at 1912 ms

The first run is near 500 ms. The second block starts at about 1200 ms, the reschedule at 1400 ms moves the deadline to about 1900 ms, and the handler runs once, near 1912 ms. The exact milliseconds depend on tick rounding and boot time. The point is the count: two calls, one run in both cases, but at different times.

Debounce a button

A mechanical switch bounces for several milliseconds, producing a burst of interrupts. The usual fix is to wait until the signal has been stable for a short period. k_work_reschedule does it directly: every interrupt pushes the deadline out, and the handler runs only after the last one:

c
#include <zephyr/kernel.h>
#include <zephyr/drivers/gpio.h>

static const struct gpio_dt_spec btn = GPIO_DT_SPEC_GET(DT_ALIAS(sw0), gpios);
static struct gpio_callback btn_cb;
static struct k_work_delayable debounce_work;

static void debounced(struct k_work *work)
{
	int level = gpio_pin_get_dt(&btn);

	printk("button is now %s\n", level ? "pressed" : "released");
}

static void button_isr(const struct device *dev, struct gpio_callback *cb,
		       uint32_t pins)
{
	k_work_reschedule(&debounce_work, K_MSEC(30));
}

int main(void)
{
	k_work_init_delayable(&debounce_work, debounced);
	gpio_pin_configure_dt(&btn, GPIO_INPUT);
	gpio_pin_interrupt_configure_dt(&btn, GPIO_INT_EDGE_BOTH);
	gpio_init_callback(&btn_cb, button_isr, BIT(btn.pin));
	gpio_add_callback(btn.port, &btn_cb);
	return 0;
}

On both edges, the ISR reschedules the handler for 30 ms later. A press that bounces five times in 4 ms triggers five reschedules, and the handler runs once, 30 ms after the last bounce, reads the settled level, and prints one line:

Text
*** Booting Zephyr OS build v4.2.0 ***
button is now pressed
button is now released

k_work_reschedule is safe to call from an ISR, which is why the pattern works. The handler reads the pin instead of trusting the edge that woke it, which also makes the result correct if a bounce ended on the opposite level.

A timeout that is pushed back by activity

The same call implements an inactivity timeout. A radio that should sleep after ten idle seconds is rescheduled on each received packet:

c
static struct k_work_delayable idle_work;

static void go_to_sleep(struct k_work *work)
{
	printk("idle for 10 s, sleeping\n");
}

void on_packet(void)
{
	k_work_reschedule(&idle_work, K_SECONDS(10));
}

void init(void)
{
	k_work_init_delayable(&idle_work, go_to_sleep);
	k_work_reschedule(&idle_work, K_SECONDS(10));
}

Each packet moves the sleep deadline ten seconds into the future. When traffic stops, the handler runs once. This costs one timer and no polling loop. Cancel the timeout with k_work_cancel_delayable(&idle_work) when sleeping becomes unnecessary.

A periodic task

A delayable work item can repeat by rescheduling itself at the end of its handler:

c
static struct k_work_delayable poll_work;

static void poll_sensor(struct k_work *work)
{
	struct k_work_delayable *d = k_work_delayable_from_work(work);

	printk("poll\n");
	k_work_reschedule(d, K_SECONDS(1));
}

void start_polling(void)
{
	k_work_init_delayable(&poll_work, poll_sensor);
	k_work_schedule(&poll_work, K_NO_WAIT);
}

This runs one second after each handler finishes, so the period is one second plus the handler's run time, and it drifts. For a fixed period that does not drift, use a k_timer that submits a plain work item, as in the timer post, or compute the next deadline from a fixed start with K_TIMEOUT_ABS_MS. The self-rescheduling form is simple and suits tasks where the gap between runs matters more than the exact rate, such as retries.

Status and cancellation

You can ask what an item is doing:

c
if (k_work_delayable_is_pending(&job)) {
	printk("scheduled or queued\n");
}
k_ticks_t left = k_work_delayable_remaining_get(&job);

k_work_delayable_is_pending is true while the item is waiting for its delay, queued or running. k_work_delayable_remaining_get returns the ticks until it is due. To cancel, k_work_cancel_delayable(&job) stops a scheduled item and returns immediately. If the handler is already running, it cannot be stopped, and k_work_cancel_delayable_sync waits until it finishes, which is thread-only. The next post covers the synchronous forms.

Pitfalls

**Using k_work_schedule for a debounce.** The first deadline stands, so a late bounce is processed too early. Use k_work_reschedule.

**Using k_work_reschedule for a rate limit.** A busy source keeps pushing the deadline out, and the handler never runs. Use k_work_schedule when you need the work done within a bound.

Initializing the item more than once. k_work_init_delayable on a pending item corrupts state. Initialize once at startup.

Putting the item on a stack. The kernel keeps a pointer to it until it runs. Keep it static or in long-lived storage.

Slow handlers. The same system queue rules apply. Keep handlers short, or use a dedicated queue, as covered in the later post.

Choosing the delay

The delay is a k_timeout_t, so K_MSEC(30), K_SECONDS(10) and K_TICKS(n) all work, and the handler runs at the next workqueue opportunity after it expires, not at the exact tick. If the system workqueue is busy with a long handler, the delayed item waits behind it. The delay is therefore a lower bound on when the handler starts, and the upper bound depends on what else is queued. When the timing of the start matters to within a millisecond, a hardware timer or a dedicated high-priority queue is the right tool, and this mechanism is for work where tens of milliseconds of jitter are acceptable.

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.