一、定时器初始化
void hrtimer_init(struct hrtimer *timer, clockid_t clock_id, enum hrtimer_mode mode);
1 2 3 4 5 6 7 8 9 10
| 参数timer是hrtimer指针, 参数clock_id有如下常用几种选项: CLOCK_REALTIME CLOCK_MONOTONIC 参数mode有如下几种选项: HRTIMER_MODE_ABS = 0x0, HRTIMER_MODE_REL = 0x1, HRTIMER_MODE_PINNED = 0x02, HRTIMER_MODE_ABS_PINNED = 0x02, HRTIMER_MODE_REL_PINNED = 0x03,
|
二、启动定时器
hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode);
1 2 3
| 参数timer是hrtimer指针 参数tim是时间,可以使用ktime_set()函数设置时间, 参数mode和初始化的mode参数一致
|
三、设置超时时间
1 2 3 4 5 6 7
|
ktime_t ktime_set(const long secs, const unsigned long nsecs);
hrtimer_forward_now(struct hrtimer *timer, ktime_t interval)
|
四、设置回调函数
1 2
| struct hrtimer timer; timer.function = hr_callback;
|
五、关闭定时器
int hrtimer_cancel(struct hrtimer *timer);
使用例子:hrtimer.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| #include <linux/module.h> #include <linux/kernel.h> #include <linux/hrtimer.h> #include <linux/jiffies.h>
static struct hrtimer timer; ktime_t kt;
static enum hrtimer_restart hrtimer_hander(struct hrtimer *timer) { printk("I am in hrtimer hander\r\n"); hrtimer_forward(timer,timer->base->get_time(),kt); return HRTIMER_RESTART; } static int __init test_init(void) { printk("---------%s-----------\r\n",__func__); kt = ktime_set(0,1000000); hrtimer_init(&timer,CLOCK_MONOTONIC,HRTIMER_MODE_REL); hrtimer_start(&timer,kt,HRTIMER_MODE_REL); timer.function = hrtimer_hander; return 0; } static void __exit test_exit(void) { hrtimer_cancel(&timer); printk("------------test over---------------\r\n"); } module_init(test_init); module_exit(test_exit); MODULE_LICENSE("GPL");
|