In order to do some work periodically, we can add pointer to our function to kernel task queue, then kernel will execute it automatically.

Every time the function was executed, it need to add itself to kernel task queue again, if it wants to be executed in the future.

First, the header files (This time I will make it a kernel module):
#include <linux/kernel.h> /* We're doing kernel work */
#include <linux/module.h> /* Specifically, a module */
#include <linux/workqueue.h> /* We scheduale tasks here */
#include <linux/sched.h> /* We need to put ourselves to sleep and wake up later */
#include <linux/init.h> /* For __init and __exit */
#include <linux/interrupt.h> /* For irqreturn_t */
#include <asm/delay.h>
#include <linux/delay.h>

Second, define the variable needed to use.
struct delayed_work led_event;
static void led_event_work_func(struct work_struct **work);

Third, write the working function.
void led_event_work_func(struct work_struct **work)
{
        printk(KERN_INFO "Once execution\n");
        schedule_delayed_work(&led_event,1000);      //Add myself to task queue again, and delay for 1000ms before execution
}

Last, the init and cleanup function of kernel module
int __init init_module()
{
        printk(KERN_INFO "init_module\n");
        INIT_DELAYED_WORK(&led_event, led_event_work_func);  //Initialize work struct
        schedule_delayed_work(&led_event,1000);              //First add work to task queue, and delay 1000ms before execution
        return 0;
}

void __exit cleanup_module()
{
        cancel_delayed_work(&led_event);                     //Remove work from task queue
        printk(KERN_INFO "cleanup_module\n");
}

-- ChenLi - 07 Aug 2013
Topic revision: r2 - 08 Feb 2014, HarlanStenn
 

This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding Network Time Foundation Community Wiki? Send feedback