二十二、linux定时器
一、Linux 定時器介紹
?????????在 Linux 內核中, 定時器叫做內核定時器, 內核定時器用于控制某個函數, 也就是定時器將要處理的函數在未來的某個特定的時間內執行。 內核定時器注冊的處理函數只執行一次, 即不是循環執行的。 定時器的使用范圍(延后執行某個操作, 定時查詢某個狀態; 前提是對時間要求不高的地方) 。
????????Hz: 系統時鐘通過 CONFIG_HZ 來設置, 范圍是 100-1000; HZ 決定使用中斷發生的頻率。 如果就沒有定義的話, 默認是 100, 例: 1/200 = 5ms, 說明 4412 中是 5ms 產生一次時鐘中斷。內核的全局變量 jiffies: (記錄內核自啟動來的節拍數, 啟動的時候初始化為 0, 內核之啟動以來, 產生的中斷數) 時鐘中斷, 每產生一個中斷, jiffies 就加 1。 可以用來計算流逝時間和時間管理, jiffies 除以Hz 得到內核自啟動以來的秒數。
二、數據類型:struct timer_list
struct timer_list {/** All fields that change during normal runtime grouped to the* same cacheline*/struct list_head entry;unsigned long expires;struct tvec_base *base;void (*function)(unsigned long);unsigned long data;int slack;#ifdef CONFIG_TIMER_STATSint start_pid;void *start_site;char start_comm[16]; #endif #ifdef CONFIG_LOCKDEPstruct lockdep_map lockdep_map; #endif };包含的主要成員:
-
struct list_head entry 雙向鏈表
-
expires:定時器超時的時間,以linux的jiffies來衡量,記錄什么時候產生時鐘中斷。
-
struct tvec_base *base: 管理時鐘的結構體
-
void (*function)(unsigned long):定時器超時處理函數。
-
data:傳遞到超時處理函數的參數,主要在多個定時器同時使用時,區別是哪個timer超時。
三、主要相關的API函數
init_timer(struct timer_list*):定時器初始化函數; add_timer(struct timer_list*):往系統添加定時器; mod_timer(struct timer_list *, unsigned long jiffier_timerout):修改定時器的超時時間為jiffies_timerout; timer_pending(struct timer_list *):定時器狀態查詢,如果在系統的定時器列表中則返回1,否則返回0; del_timer(struct timer_list*):刪除定時器。四、使用簡例
#include "linux/module.h" #include "linux/timer.h" #include "linux/jiffies.h"struct timer_list demo_timer;static void time_func(unsigned long data) {printk("%s ,secs = %ld!\n",(char *)data,jiffies/HZ);mod_timer(&demo_timer,jiffies + 5*HZ); }static int __init mytimer_init(void) {printk("mytimer_init!\n");setup_timer(&demo_timer,time_func,(unsigned long) "demo_timer!");demo_timer.expires = jiffies + 1*HZ;add_timer(&demo_timer);return 0; }static void __exit mytimer_exit(void) {printk("mytimer_exit!\n");del_timer(&demo_timer); }module_init(mytimer_init); module_exit(mytimer_exit);MODULE_LICENSE("Dual BSD/GPL");五、運行結果
?
總結
以上是生活随笔為你收集整理的二十二、linux定时器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 二十一、SPI设备驱动及应用(二)
- 下一篇: 嵌入式Linux学习问题解决记录