linux-sysprog · beginner · ~10 min
Absolute-time scheduling — the core of timerfd, setitimer, every cron alternative.
Reason about a one-shot timer using absolute times: has it fired yet, and how long until it does? This is pure arithmetic on millisecond values — no real timer is used.
Implement two functions about a timer set to fire at an absolute time fire_at_ms:
int timer_due(long now_ms, long fire_at_ms);
long timer_remaining_ms(long now_ms, long fire_at_ms);
now_ms: the current time in milliseconds.fire_at_ms: the absolute moment the timer is set to fire, in milliseconds.timer_due returns 1 if the timer has fired (fire_at_ms <= now_ms), else 0.timer_remaining_ms returns how many milliseconds remain until it fires, or 0 if it is already due (never negative).timer_due(1000, 1500) -> 0 (still in the future)
timer_due(2000, 1500) -> 1 (already past)
timer_due(1500, 1500) -> 1 (exactly due)
timer_remaining_ms(1000, 1500) -> 500
timer_remaining_ms(2000, 1500) -> 0 (overdue, clamped)
now_ms == fire_at_ms: due, 0 remaining.timerfd lets you turn a timer into a file descriptor. The core idea: 'absolute moment X in the future'. Once you internalise that, the whole API makes sense.
The current time now_ms and the absolute fire time fire_at_ms, both in milliseconds.
timer_due returns 1 if fire_at_ms <= now_ms else 0; timer_remaining_ms returns ms left, clamped to 0.
Remaining time is never negative. Pure arithmetic, no syscalls.
int timer_due(long now_ms, long fire_at_ms) { /* TODO */ return 0; }
long timer_remaining_ms(long now_ms, long fire_at_ms) { /* TODO */ return 0; }
Using subtraction without checking for negative — fire - now may go negative once due.
fire_at_ms == now_ms (just due). Far-future timer. Already-past timer.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.