libevent::事件::定时器

 

 

 

复制代码
#include <cstdio>
#include <errno.h>
#include <sys/types.h>
#include <event.h>
#include <event2/event.h>
#include <event2/event_struct.h>
#include <event2/event-config.h>
#include <event2/util.h>

int lasttime;

static void
timeout_cb(int fd, short event, void *arg)
{
    struct timeval tv;
    struct event *timeout = (struct event *)(arg);
    int newtime = time(NULL);

    printf("%s: called at %d: %d\n", "timeout_cb", newtime, newtime - lasttime);
    lasttime = newtime;

    evutil_timerclear(&tv);
    tv.tv_sec = 2;

    // 重新添加定时事件(定时事件触发后默认自动删除)  
    event_add(timeout, &tv);
}

int main(int argc, char **argv)
{
    struct event timeout;
    struct timeval tv;

    //初始化event环境
    event_init();

    //设置事件
    evtimer_set(&timeout, timeout_cb, &timeout);

    evutil_timerclear(&tv);
    tv.tv_sec = 2;    //2s

    //注册事件
    event_add(&timeout, &tv);

    lasttime = time(NULL);

    //等待,分发,处理事件
    event_dispatch();

    return (0);
}
复制代码

 

posted @ 2019-01-16 22:38  osbreak  阅读(542)  评论(0编辑  收藏  举报