linux-sysprog · beginner · ~10 min

One-shot timer: 'is now past the fire time?'

Absolute-time scheduling — the core of timerfd, setitimer, every cron alternative.

Challenge

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.

Task

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);

Input

  • now_ms: the current time in milliseconds.
  • fire_at_ms: the absolute moment the timer is set to fire, in milliseconds.

Output

  • 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).

Example

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)

Edge cases

  • now_ms == fire_at_ms: due, 0 remaining.
  • An overdue timer reports 0 remaining, not a negative number.

Why this matters

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.

Input format

The current time now_ms and the absolute fire time fire_at_ms, both in milliseconds.

Output format

timer_due returns 1 if fire_at_ms <= now_ms else 0; timer_remaining_ms returns ms left, clamped to 0.

Constraints

Remaining time is never negative. Pure arithmetic, no syscalls.

Starter code

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; }

Common mistakes

Using subtraction without checking for negative — fire - now may go negative once due.

Edge cases to handle

fire_at_ms == now_ms (just due). Far-future timer. Already-past timer.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.