目录
- 数据结构
- 常见操作
- 1. 创建定时事件
- 2. 触发定时事件
- 3. 引用计数与递归保护
- 总结
本文主要基于 Redis 6.2 的源代码,深入剖析定时事件(Timer Event)的数据结构设计及其常见的操作流程。
数据结构
在 Redis 内部,定时任务事件是通过 aeTimeEvent 结构体进行定义和管理的,其核心代码定义如下:
/* Time event structure */
typedef struct aeTimeEvent {
// 标识符
long long id; /* time event identifier. */
// 定时纳秒数
monotime when;
// 定时回调函数
aeTimeProc *timeProc;
// 注销定时器时候的回调函数
aeEventFinalizerProc *finalizerProc;
void *clientData;
struct aeTimeEvent *prev;
struct aeTimeEvent *next;
int refcount; /* refcount to prevent timer events from being
* freed in recursive time event calls. */
} aeTimeEvent;
常见操作
1. 创建定时事件
Redis 中最关键且周期性执行的定时函数是 serverCron。由于 Redis 中的定时任务数量通常较少,系统并未采用严格的过期时间排序策略,而是利用 id 自增结合头插法的方式,确保链表保持基本有序的状态。
if (aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL) == AE_ERR) {
serverPanic("Can't create event loop timers.");
exit(1);
}
//创建定时器对象
long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds,
aeTimeProc *proc, void *clientData,
aeEventFinalizerProc *finalizerProc)
{
long long id = eventLoop->timeEventNextId++;
aeTimeEvent *te;
te = zmalloc(sizeof(*te));
if (te == NULL) return AE_ERR;
te->id = id;
te->when = getMonotonicUs() + milliseconds * 1000;
te->timeProc = proc;
te->finalizerProc = finalizerProc;
te->clientData = clientData;
te->prev = NULL;
// 头插法
te->next = eventLoop->timeEventHead;
te->refcount = 0;
if (te->next)
te->next->prev = te;
eventLoop->timeEventHead = te;
return id;
}

2. 触发定时事件
Redis 借助 IO 复用机制来驱动定时任务的触发过程。
系统需要查找距离当前时刻最近的定时事件,这一逻辑由 usUntilEarliestTimer 函数负责实现。
/* How many microseconds until the first timer should fire.
* If there are no timers, -1 is returned.
*
* Note that's O(N) since time events are unsorted.
* Possible optimizations (not needed by Redis so far, but...):
* 1) Insert the event in order, so that the nearest is just the head.
* Much better but still insertion or deletion of timers is O(N).
* 2) Use a skiplist to have this operation as O(1) and insertion as O(log(N)).
*/
static int64_t usUntilEarliestTimer(aeEventLoop *eventLoop) {
aeTimeEvent *te = eventLoop->timeEventHead;
if (te == NULL) return -1;
aeTimeEvent *earliest = NULL;
while (te) {
if (!earliest || te->when < earliest->when)
earliest = te;
te = te->next;
}
monotime now = getMonotonicUs();
return (now >= earliest->when) ? 0 : earliest->when - now;
}
该查找过程的时间复杂度可能较高,在实际应用中需结合具体场景评估性能影响。
此外,还需更新剩余过期时间。这是因为前文提到的 IO 复用可能会因其他 IO 事件的返回而提前唤醒,因此必须重新计算等待时间。
if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT))
usUntilTimer = usUntilEarliestTimer(eventLoop);
if (usUntilTimer >= 0) {
tv.tv_sec = usUntilTimer / 1000000;
tv.tv_usec = usUntilTimer % 1000000;
tvp = &tv;
} else {
if (flags & AE_DONT_WAIT) {
// 不等待
tv.tv_sec = tv.tv_usec = 0;
tvp = &tv;
} else {
/* Otherwise we can block */
tvp = NULL; /* wait forever */
}
}
3. 执行定时事件
一次性定时事件在执行完毕后会被直接删除;而周期性定时事件在执行完成后,会重新被添加回链表中以等待下一次触发。
/* Process time events */
static int processTimeEvents(aeEventLoop *eventLoop) {
int processed = 0;
aeTimeEvent *te;
long long maxId;
te = eventLoop->timeEventHead;
maxId = eventLoop->timeEventNextId-1;
monotime now = getMonotonicUs();
// 删除定时器
while(te) {
long long id;
// 下一轮中对事件进行删除
/* Remove events scheduled for deletion. */
if (te->id == AE_DELETED_EVENT_ID) {
aeTimeEvent *next = te->next;
/* If a reference exists for this timer event,
* don't free it. This is currently incremented
* for recursive timerProc calls */
if (te->refcount) {
te = next;
continue;
}
if (te->prev)
te->prev->next = te->next;
else
eventLoop->timeEventHead = te->next;
if (te->next)
te->next->prev = te->prev;
if (te->finalizerProc) {
te->finalizerProc(eventLoop, te->clientData);
now = getMonotonicUs();
}
zfree(te);
te = next;
continue;
}
if (te->id > maxId) {
te = te->next;
continue;
}
if (te->when <= now) {
int retval;
id = te->id;
te->refcount++;
// timeProc 函数返回值 retVal 为时间事件执行的间隔
retval = te->timeProc(eventLoop, id, te->clientData);
te->refcount--;
processed++;
now = getMonotonicUs();
if (retval != AE_NOMORE) {
te->when = now + retval * 1000;
} else {
// 如果超时了,那么标记为删除
te->id = AE_DELETED_EVENT_ID;
}
}
// 执行下一个
te = te->next;
}
return processed;
}
总结
优点:实现逻辑简单直观。 缺点:当定时任务数量庞大时,遍历链表的效率较低。
到此这篇关于 Redis 定时任务原理的实现的文章就介绍到这了,更多相关 Redis 定时任务内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!