Technical skill

Linux time: timers

Make a program wait or wake up later

A kitchen timer rings after a chosen delay. Programs need the same ability: wait before trying again, wake up at a chosen time (a deadline), or notify another part of the program that time has passed. The operating system can mark a timer ready, but it cannot promise that the program runs at that exact instant. The scheduler may be busy, so the response can be late.

For example, a task that sleeps one second after each round of work will drift if each round itself takes time. Scheduling each round against a fixed timeline prevents the work duration from adding to every interval. Choose the clock that matches the deadline. A five-second delay should use an elapsed-time clock; an alarm for 8:00 on a calendar needs the wall clock.

Choose a clock and a kind of notification

CLOCK_MONOTONIC measures elapsed time from an unspecified starting point. It does not jump when someone sets the wall clock, though Linux may adjust its rate to correct clock drift. It stops counting while the system is suspended. Use CLOCK_BOOTTIME when the interval should include suspended time. CLOCK_REALTIME represents date and time on a calendar, so it can jump when the system clock changes.

Linux has several timer interfaces. clock_nanosleep() pauses the part of a program doing the work, called its thread, until a time or deadline. A POSIX timer, using timer_create(), can send a notification, often a signal that a program handles with a response function. Linux timerfd makes timer expirations available as a file descriptor. A program can register that descriptor in an event loop, the part of an application that waits for many inputs such as network data or timer events. These choices fit different designs; they do not change the scheduler's timing.

Wait for an absolute deadline

This C example sets a deadline five seconds after the current monotonic time. C is a programming language; the code uses POSIX, a shared interface standard for Unix-like systems:

struct timespec deadline;
clock_gettime(CLOCK_MONOTONIC, &deadline);
deadline.tv_sec += 5;
int rc = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME,
                         &deadline, NULL);

The deadline is a time value with seconds and smaller fractions. TIMER_ABSTIME tells clock_nanosleep() to wait until that absolute deadline rather than sleeping for a fresh relative interval. The example omits headers and full error handling. Production code should check rc, the returned status. clock_nanosleep() returns an error number directly instead of returning -1 and setting errno, as many system calls do.

A signal handler is code set up to respond when a signal arrives. If one runs during the wait, clock_nanosleep() returns EINTR. For an absolute wait, retry with the same deadline. If the deadline has passed, the call returns without another five-second delay. Recomputing a new deadline after every interruption would extend the wait.

Count timer events without losing time

Create a timerfd with the chosen clock, set its first expiration and optional repeat interval, then register it with the event loop using poll or epoll. When the descriptor becomes readable, read its 64-bit expiration count. The count says how many expirations occurred since the last successful read or timer-setting change. It can exceed one if the loop was busy, so decide whether to catch up, skip missed periods, or plan the next deadline from the original timeline. Close the descriptor when it is no longer needed.

Signal-based timers need a handler design that keeps unsafe or lengthy work out of the handler. Choose the clock and notification method according to what the program should do when time expires. A delayed wakeup is normal under load.

Interactive exercises

Materials

Skillsets
Skillset Linux for backend developer preview
image descriptionLinux for backend developer
by Artem Naumenko (fb)
16 users
Skillset Linux administrator preview
image descriptionLinux administrator
by Infinite Education
3080 users
Skillset Devops preview
image descriptionDevops
by Ajay Kumar
2004 users
Skillset Devops preview
image descriptionDevops
by Dio
3 users
Do you know that ...?
Any useful or interesting facts about the skill. Any peace of information would be useful