linux中定时器,比较简单。
struct timer_list
{
struct list_head list; //linux中对所有定时器实行链表管理,此为链表头结点
unsigned long expires; //定时器到期时间
unsigned long data; //此参数最后传入定时处理函数,类似于线程中的arg
void (*function)(unsigned long); //定时器超时执行函数
};
步骤:
init_timer(struct timer_list *timer);//初始化定时器
add_timer(struct timer_list *timer);//启动定时器
del_timer(struct timer_list *timer);//删除定时器
简单实例:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/sched.h>
static struct timer_list my_timer;
static unsigned long args = 0;
static void my_timer_func(unsigned long arg)
{
printk("定时器打印 arg = %ld \n", arg);
args += 1;
my_timer.expires = jiffies + msecs_to_jiffies(5 * 1000);//重启定时器
my_timer.data = args;
my_timer.function = my_timer_func;
add_timer(&my_timer);
}
static int __init my_timer_init(void)
{
printk("[yb] init entry\n");
init_timer(&my_timer);
my_timer.expires = jiffies + msecs_to_jiffies(2 * 1000);
my_timer.data = 250;
my_timer.function = my_timer_func;
add_timer(&my_timer);
printk("[yb] init exit\n");
return 0;
}
static void __exit my_timer_exit(void)
{
printk("[yb] exit entry\n");
del_timer(&my_timer);
printk("[yb] exit!\n");
}
module_init(my_timer_init);
module_exit(my_timer_exit);
MODULE_LICENSE("GPL");
Makefile文件
#ifneq ($(KERNELRELEASE),)
obj-m := timer_s01.o
#else
KDIR := /lib/modules/$(shell uname -r)/build
all:
make -C $(KDIR) M=$(shell pwd) modules
clean:
make -C $(KDIR) M=$(shell pwd) clean
#endif
编译完成后:
insmod timer_s01.ko
kernel打印:
<4>[ 4216.980183] 定时器打印 arg = 122
<4>[ 4221.987377] 定时器打印 arg = 123
<4>[ 4226.995415] 定时器打印 arg = 124
<4>[ 4232.003418] 定时器打印 arg = 125
<4>[ 4237.011527] 定时器打印 arg = 126
<4>[ 4242.019568] 定时器打印 arg = 127
<4>[ 4247.027698] 定时器打印 arg = 128
<4>[ 4252.035926] 定时器打印 arg = 129
<4>[ 4257.049528] 定时器打印 arg = 130
<4>[ 4262.051844] 定时器打印 arg = 131
<4>[ 4267.059999] 定时器打印 arg = 132
<4>[ 4272.070906] 定时器打印 arg = 133
<4>[ 4277.076879] 定时器打印 arg = 134
5s打印一次。