Linux的hrtimer高精度定时器的使用

时间:2021-12-19 00:25:32
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/hrtimer.h>
#include <linux/ktime.h>

MODULE_LICENSE("GPL");

#define MS_TO_NS(x) (x * 1E6L)//这个是定时器的超时时间,到了这个时间就会调用回调函数。
static struct hrtimer hr_timer;

enum hrtimer_restart my_hrtimer_callback( struct hrtimer *timer )
{
printk( "my_hrtimer_callback called (%ld).\n", jiffies );
  hrtimer_start( &hr_timer, ktime, HRTIMER_MODE_REL );//到了这里再次调用就会不断的调用这个回调函数,两次调用时间间隔正是设定的超时时间
return HRTIMER_NORESTART;}int init_module( void ){ ktime_t ktime; unsigned long delay_in_ms = 200L; printk("HR Timer module installing\n"); ktime = ktime_set( 0, MS_TO_NS(delay_in_ms) ); hrtimer_init( &hr_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL ); hr_timer.function = &my_hrtimer_callback; printk( "Starting timer to fire in %ldms (%ld)\n", delay_in_ms, jiffies ); hrtimer_start( &hr_timer, ktime, HRTIMER_MODE_REL ); return 0;}void cleanup_module( void ){ int ret; ret = hrtimer_cancel( &hr_timer ); if (ret) printk("The timer was still in use...\n"); printk("HR Timer module uninstalling\n"); return;}
注意:该定时器是异步执行的,类似于软中断和tasklet实现机制