/** * Check timer list for pending timeout */ MWBOOL GdTimeout(void) { MWTIMER *n, *t = timerlist; signed long tempTimeout = 0; gettimeofday(¤t_time, NULL); while(t) { n = t->next; tempTimeout = time_to_expiry(&t->timeout); if( tempTimeout<= 0) { t->callback(t->arg); if (t->type == MWTIMER_ONESHOT) GdDestroyTimer(t); /* One shot timer, is finished delete it now */ else calculate_timeval (&t->timeout, t->period); /* Periodic timer needs to be reset */ } else { if( tempTimeout>0 && tempTimeout>t->period ) calculate_timeval (&t->timeout, t->period); } t = n; } if(mainloop_timeout.tv_sec > 0 || mainloop_timeout.tv_usec > 0) if(time_to_expiry(&mainloop_timeout) <= 0) return TRUE; return FALSE; }
/** * ?? Internal function. * * @param tv ?? * @param timeout ?? * @return ?? */ MWBOOL GdGetNextTimeout(struct timeval *tv, MWTIMEOUT timeout) { signed long i, lowest_timeout; MWTIMER *t = timerlist; if(!timeout && !timerlist) return FALSE; gettimeofday(¤t_time, NULL); if(timeout) { calculate_timeval(&mainloop_timeout, timeout); lowest_timeout = time_to_expiry(&mainloop_timeout); } else { lowest_timeout = time_to_expiry(&t->timeout); mainloop_timeout.tv_sec = -1; t = t->next; } while(t) { i = time_to_expiry(&t->timeout); if(i < lowest_timeout) lowest_timeout = i; t = t->next; } if(lowest_timeout <= 0) { tv->tv_sec = 0; tv->tv_usec = 0; } else { tv->tv_sec = lowest_timeout / 1000; tv->tv_usec = (lowest_timeout % 1000) * 1000; } return TRUE; }
/** * Create a new one-shot timer. * * @param timeout number of milliseconds before the timer should activate * @param callback Callback function to call when timer fires. * @param arg Opaque argument to pass to callback function. * @return Timer handle. NOTE that this is automatically destroyed * after the callback function has been called. */ MWTIMER *GdAddTimer(MWTIMEOUT timeout, MWTIMERCB callback, void *arg) { MWTIMER *newtimer; if(!(newtimer = malloc(sizeof(MWTIMER)))) return NULL; gettimeofday(¤t_time, NULL); if(timerlist) timerlist->prev = newtimer; calculate_timeval(&newtimer->timeout, timeout); newtimer->callback = callback; newtimer->arg = arg; newtimer->next = timerlist; newtimer->prev = NULL; newtimer->type = MWTIMER_ONESHOT; newtimer->period = timeout; timerlist = newtimer; return newtimer; }
/** * Restart a timer. * * @param timer Timer to restart. */ void GdRestartTimer(MWTIMER *timer) { calculate_timeval (&timer->timeout, timer->period); }