libevent timer

创建计时器event按照如下步骤:

    event_init();   //初始化event_base

    //创建timer event
    struct event timer_ev;
    evtimer_set(&timer_ev, callback_fn, NULL);
    //evtimer_set(ev, cb, arg)宏相当于event_set(ev, -1, 0, cb, arg)

    //添加timer event到侦听中
    struct timeval tv;
    tv.tv_sec = 5;  //5 seconds
    tv.tv_usec = 0;
    evtimer_add(&timer_ev, &tv);
    //evtimer_add(ev, tv)宏相当于event_add(ev, tv)

    event_dispatch();

注意:如上创建的timer event不是persistent的(因为evtimer_set等价的event_set(ev, -1, 0, cb, arg)的第三个参数没有指定EV_PERSIST),即该事件在被触发一次(timeout达到5秒)之后即返回,不再参与到libevent的下次侦听了。


因此,想重复定时器,需要反复增加定时器

static void clock_handler(const int fd, const short which, void *arg) {
    struct timeval t = {.tv_sec = 1, .tv_usec = 0};
    static bool initialized = false;

    if (initialized) {
        /* only delete the event if it's actually there. */
        evtimer_del(&clockevent);
    } else {
        initialized = true;
    }

    evtimer_set(&clockevent, clock_handler, 0);
    event_base_set(main_base, &clockevent);
    evtimer_add(&clockevent, &t);

    set_current_time();
}


你可能感兴趣的:(timer,struct,null,delete,callback)