c - ev_timer callback is called earlier than it should be -
i have problem ev_timer of libev, please @ code below:
static void timeout_cb(struct ev_loop *loop, ev_timer *timer, int revent) { printf("got timeout event, current time %s\n", get_current_time()); } int main(int argc, char *argv[]) { struct ev_loop *loop = ev_loop_new(0); ev_timer_init(&timer, timeout_cb, 5.0, 0.0); ev_timer_start(loop, &timer); ev_run(loop, evrun_nowait); // callback should not called ev_timer_stop(loop, &timer); // stop timer sleep(5); // sleep 5 seconds, 5 timer's timeout value // restart timer ev_timer_init(&timer, timeout_cb, 5.0, 0.0); ev_timer_start(loop, &timer); printf("timer start at: %s\n", get_current_time()); printf("timer remaining: %f\n", ev_timer_remaining(loop, &timer)); ev_run(loop, evrun_nowait); return 0; }
the output is:
timer start at: 14:53:49:137 timer remaining: 5.0000 got timeout event, current time 14:53:49:137
this strange, because after restart timer timer trigger immediately, should 5 second later. found reason sleep(5). change sleep(4) timer callback not called. i'm confused liebev's timer functionality. have misunderstand timer? , how let timer callback called after timeout elapse after timer restart?
i don't claim expert in libev, found using ev_suspend(loop) , ev_resume(loop) prevent behaviour seeing. man page:
ev_suspend (loop) ev_resume (loop) these 2 functions suspend , resume event loop, use when loop not used while , timeouts should not processed.
e.g.:
ev_run(loop, evrun_nowait); // callback should not called ev_timer_stop(loop, &timer); // stop timer ev_suspend(loop); // suspend timer processing sleep(5); // sleep 5 seconds, 5 timer's timeout value ev_resume(loop); // resume timer processing // restart timer ev_timer_init(&timer, timeout_cb, 5.0, 0.0); ev_timer_start(loop, &timer);
also found possible solution use ev_timer_again() instead of ev_timer_start() prevents behaviour reported.
e.g.:
ev_timer_stop(loop, &timer); // stop timer sleep(5); // sleep 5 seconds, 5 timer's timeout value // restart timer ev_timer_again(loop, &timer);
Comments
Post a Comment