Kernel Timer Demo
Description
Demonstrates kernel timers for periodic execution. Timers run in softirq context and are useful for polling, timeouts, and scheduled tasks.
Features
- Periodic timer execution (fires 10 times)
- Configurable interval via module parameter
- Jiffies and time conversion
- Safe timer cancellation
Build & Test
make
# Default: 1 second interval
sudo insmod timer_demo.ko
# Custom interval: 500ms
sudo insmod timer_demo.ko timer_interval_ms=500
# Watch timer fire
dmesg -w
# Unload (cancels timer)
sudo rmmod timer_demo
Expected Output
=== Kernel Timer Demo ===
Timer interval: 1000 ms
HZ (timer frequency): 250
Jiffies at init: 4294892314
Timer started - will fire 10 times
Timer fired! Count: 1, jiffies: 4294892564
Timer rescheduled for 1000 ms
Timer fired! Count: 2, jiffies: 4294892814
Timer rescheduled for 1000 ms
...
Timer fired! Count: 10, jiffies: 4294895064
Timer finished after 10 callbacks
(On rmmod):
Timer was already inactive
Timer demo: Fired 10 times total
Module Parameters
timer_interval_ms: Interval in milliseconds (default: 1000)
# Fast timer (100ms)
sudo insmod timer_demo.ko timer_interval_ms=100
# Slow timer (5 seconds)
sudo insmod timer_demo.ko timer_interval_ms=5000
Time Concepts
Jiffies
- Kernel’s tick counter (increments HZ times per second)
- System-dependent: HZ = 100, 250, or 1000
Time Conversion
msecs_to_jiffies(1000) // 1 second in jiffies
jiffies_to_msecs(HZ) // HZ jiffies to milliseconds
Use Cases
- Polling: Check device status periodically
- Timeouts: Implement operation timeouts
- Throttling: Rate-limit operations
- Heartbeat: Keep-alive mechanisms
- Delayed work: Alternative to work queues for simple cases
Learning Points
- Timer callback runs in softirq (atomic) context
- Cannot sleep in timer callback
- Use
mod_timer()for rescheduling - Use
del_timer_sync()for safe cancellation - Timers are not perfectly accurate (depends on HZ)
Advanced: High-Resolution Timers
For sub-jiffy precision, use hrtimers (not covered in this example):
#include <linux/hrtimer.h>
// See kernel documentation for hrtimer API