c - 在 C 中实现定时事件

标签 c linux timer pthreads intervals

我正在编写一个简单的应用程序来检查 Linux (x86/x86_64) 上某个时间间隔内的一些记录 每条记录都有自己的检查间隔,可以在 5 到 300 秒之间。 这是记录结构:

...
typedef struct record_t {
    char name[256];
    time_t last_check;
    unsigned int interval;
    unsigned long amount;
    struct record_t *next;
} struct_t;
...

和检查记录的线程:

...
/* records is a pointer to the first record in the linked list */
while(1) {
    for (current_record = records;
         current_record != NULL;
         current_record = current_record->next)
         {
            if(current_record->last_check + current_record->interval < time(0))
                update_record(current_record);
         }
    sleep(1);
}
...

记录列表的长度可以变化很大(例如从 2 到 100 000) 随着每个元素被插入列表,这将变得越来越慢...... 有没有办法优化它或每条记录都有一个触发器 所以不是用循环检查所有东西, 间隔过去时调用回调? 或多或少,我正在从 JavaScript 中寻找类似 setInterval() 的东西。

感谢一切

最佳答案

实现一个定时器轮。制作一个包含 301 个指针的数组。 不要像那样对记录进行排队,而是根据超时对它们进行排队。 有

while(1) {
    sleep (1);
    currIndx = (currIndx + 1) % 301;

    /* process the link list starting at that variable. */
    procQ = timerWheel[currIndx];

    /* re queue if necessay */

}

和排队代码:

queIndx = (currIndx + timeout) % 301;
procQ = timerWheel[queIndx];
/* add at the head of link list */

关于c - 在 C 中实现定时事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25230474/

相关文章:

C API : why are functions using returnParameters with buffer + size instead of returning char*

linux - 检查linux版本的更好方法?

linux - LD_PRELOAD 不适用于 printf

c++ - 利用计时器更新 MFC 文档/ View 应用程序

python - 使用golang实现python的定时器

c++ - 在 vector 之间共享元素的想法

c - 为什么这段代码会导致编译错误? [C、全局变量、二维数组]

c - 动态分配的堆栈和指针运算出现奇怪的内存错误

linux - 使用 vala 的示例 waf 项目

c# - 仅在自上次使用后 X 秒后执行方法