高精度定时器使用示例
#include <linux/hrtimer.h>
#include <linux/jiffies.h>
static struct hrtimer my_hrtimer;
enum hrtimer_restart my_hrtimer_callback(struct hrtimer *timer)
{
// 定时器到期时要执行的操作
// ...
return HRTIMER_NORESTART; // 或者重新启动定时器
}
static int __init my_hrtimer_init(void)
{
ktime_t ktime;
// 初始化 hrtimer
hrtimer_init(&my_hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
// 设置定时器到期时间(例如,500ms)
ktime = ktime_set(0, 500 * 1000000L); // 500ms
// 设置回调函数
my_hrtimer.function = my_hrtimer_callback;
// 启动 hrtimer
hrtimer_start(&my_hrtimer, ktime, HRTIMER_MODE_REL);
return 0;
}
static void __exit my_hrtimer_exit(void)
{
// 取消 hrtimer
hrtimer_cancel(&my_hrtimer);
}
module_init(my_hrtimer_init);
module_exit(my_hrtimer_exit);