我有ev_timer 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秒後。我發現原因是睡眠(5)。我改變它睡覺(4)然後定時器回調將不會被調用。我對liebev的計時器功能感到困惑。我對計時器有誤解嗎?如何讓定時器重啓後超時後調用定時器回調?
您應該在回答中添加更多上下文,以解釋爲什麼這會解決問題。 – Joe