From e5b0784bc24e5359e44f199af8c837ac40f84577 Mon Sep 17 00:00:00 2001 From: antirez Date: Mon, 4 Apr 2016 14:08:16 +0200 Subject: [PATCH] ae.c: Fix delay until next timer event. This fix was written by Anthony LaTorre. The old code mis-calculated the amount of time to wait till next event. --- src/ae.c | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/ae.c b/src/ae.c index bee9d4ad6..e66808a81 100644 --- a/src/ae.c +++ b/src/ae.c @@ -368,19 +368,22 @@ int aeProcessEvents(aeEventLoop *eventLoop, int flags) if (shortest) { long now_sec, now_ms; - /* Calculate the time missing for the nearest - * timer to fire. */ aeGetTime(&now_sec, &now_ms); tvp = &tv; - tvp->tv_sec = shortest->when_sec - now_sec; - if (shortest->when_ms < now_ms) { - tvp->tv_usec = ((shortest->when_ms+1000) - now_ms)*1000; - tvp->tv_sec --; + + /* How many milliseconds we need to wait for the next + * time event to fire? */ + long long ms = + (shortest->when_sec - now_sec)*1000 + + shortest->when_ms - now_ms; + + if (ms > 0) { + tvp->tv_sec = ms/1000; + tvp->tv_usec = (ms % 1000)*1000; } else { - tvp->tv_usec = (shortest->when_ms - now_ms)*1000; + tvp->tv_sec = 0; + tvp->tv_usec = 0; } - if (tvp->tv_sec < 0) tvp->tv_sec = 0; - if (tvp->tv_usec < 0) tvp->tv_usec = 0; } else { /* If we have to check for events but need to return * ASAP because of AE_DONT_WAIT we need to set the timeout