我正在编写一个简单的应用程序来检查 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/