轉自:https://blog.csdn.net/fuyuande/article/details/82193600
之前介紹了timer_list內核定時器,它的精度在毫秒級別,再高一點它就無能為力了,所幸內核提供了高精度定時器 hrtimer。
源文件在linux/kernel/hrtimer.c中。接口簡單。下面介紹一下相關接口
-
1. 定時器定義與綁定超時回調函數
-
static struct hrtimer timer;
-
-
/* 設置回調函數 */
-
timer.function = hrtimer_hander;
-
-
2. 定時器初始化
-
/*
-
* 參數timer是hrtimer指針,
-
* 參數clock_id有如下常用幾種選項:
-
* CLOCK_REALTIME //實時時間,如果系統時間變了,定時器也會變
-
* CLOCK_MONOTONIC //遞增時間,不受系統影響
-
* 參數mode有如下幾種選項:
-
* HRTIMER_MODE_ABS = 0x0, /* 絕對模式 */
-
HRTIMER_MODE_REL = 0x1, /* 相對模式 */
-
HRTIMER_MODE_PINNED = 0x02, /* 和CPU綁定 */
-
HRTIMER_MODE_ABS_PINNED = 0x02, /* 第一種和第三種的結合 */
-
HRTIMER_MODE_REL_PINNED = 0x03, /* 第二種和第三種的結合 */
-
*/
-
void hrtimer_init( struct hrtimer *timer, clockid_t clock_id, enum hrtimer_mode mode);
-
-
3. 定時器啟動
-
/*
-
* 參數timer是hrtimer指針
-
* 參數tim是時間,可以使用ktime_set()函數設置時間,
-
* 參數mode和初始化的mode參數一致
-
*/
-
hrtimer_start( struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode);
-
-
4. 設置時間
-
/*
-
* 單位為秒和納秒組合
-
*/
-
ktime_t ktime_set(const long secs, const unsigned long nsecs);
-
-
/* 設置超時時間,當定時器超時后可以用該函數設置下一次超時時間 */
-
hrtimer_forward_now( struct hrtimer *timer, ktime_t interval)
-
-
5. 注意事項:
-
定時器超時后會調用回調函數,回調函數結構類似這樣:
-
enum hrtimer_restart (*function)(struct hrtimer *);
-
-
enum hrtimer_restart {
-
HRTIMER_NORESTART, /* 不重啟定時器 */
-
HRTIMER_RESTART, /* 重啟定時器 */
-
};
-
在回調函數返回前要手動設置下一次超時時間。
-
另外,回調函數執行時間不宜過長,因為是在中斷上下文中,如果有什么任務的話,最好使用工作隊列等機制。
-
-
6. 關閉定時器
-
int hrtimer_cancel( struct hrtimer *timer);
-
-
簡單用例:
-
/*
-
* Description : 高精度定時器用例
-
* Author : mason
-
* Date : 201808
-
*/
-
-
#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( "hrtimer up\r\n");
-
-
/* 設置下次過期時間 */
-
kt = ktime_set( 3,0);
-
hrtimer_forward_now(timer, kt);
-
-
/* 該參數將重新啟動定時器 */
-
return HRTIMER_RESTART;
-
}
-
-
static int __init hrtimer_demo_init(void)
-
{
-
printk( "hello hrtimer \r\n");
-
-
kt = ktime_set( 1,10);
-
-
/* hrtimer初始化 */
-
hrtimer_init(&timer,CLOCK_MONOTONIC,HRTIMER_MODE_REL);
-
-
/* hrtimer啟動 */
-
hrtimer_start(&timer,kt,HRTIMER_MODE_REL);
-
-
/* 設置回調函數 */
-
timer.function = hrtimer_hander;
-
-
return 0;
-
}
-
-
static void __exit hrtimer_demo_exit(void)
-
{
-
/* hrtimer注銷 */
-
hrtimer_cancel(&timer);
-
printk( "bye hrtimer\r\n");
-
}
-
-
-
module_init(hrtimer_demo_init);
-
module_exit(hrtimer_demo_exit);
-
MODULE_LICENSE( "GPL");
-
參考文檔 :