我对libev的ev_timer有问题,请看下面的代码:
static void timeout_cb(struct ev_loop *loop, ev_timer *timer, int revent) {
printf("got an 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 be called
ev_timer_stop(loop, &timer); // stop the timer
sleep(5); // sleep 5 seconds, 5 is also the 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;
}
输出是:
timer start at: 14:53:49:137
timer remaining: 5.0000
got an timeout event, current time 14:53:49:137
这很奇怪,因为重新启动计时器后,计时器立即触发,但应该是 5 秒后。我发现原因是 sleep(5)。我将其更改为 sleep(4) 然后将不会调用计时器回调。我对liebev 的计时器功能感到困惑。我对计时器有误解吗?以及如何让定时器重新启动后超时后调用定时器回调?