libevent里的timer使用

来源:互联网 发布:淘宝优惠券链接打不开 编辑:程序博客网 时间:2024/06/07 04:06
/* * XXX This sample code was once meant to show how to use the basic Libevent * interfaces, but it never worked on non-Unix platforms, and some of the * interfaces have changed since it was first written.  It should probably * be removed or replaced with something better. * * Compile with: * cc -I/usr/local/include -o time-test time-test.c -L/usr/local/lib -levent */#include "stdafx.h"#include <sys/types.h>#include <event2/event-config.h>#include <sys/stat.h>#ifndef WIN32#include <sys/queue.h>#include <unistd.h>#endif#include <time.h>#ifdef _EVENT_HAVE_SYS_TIME_H#include <sys/time.h>#endif#include <fcntl.h>#include <stdlib.h>#include <stdio.h>#include <string.h>#include <errno.h>#include <event2/event.h>#include <event2/event_struct.h>#include <event2/util.h>#ifdef WIN32#include <winsock2.h>#endifstruct timeval lasttime;int event_is_persistent;static voidtimeout_cb(evutil_socket_t fd, short event, void *arg){struct timeval newtime, difference;struct event *timeout = (struct event *)arg;double elapsed;evutil_gettimeofday(&newtime, NULL);evutil_timersub(&newtime, &lasttime, &difference);elapsed = difference.tv_sec +    (difference.tv_usec / 1.0e6);printf("timeout_cb called at %d: %.3f seconds elapsed.\n",    (int)newtime.tv_sec, elapsed);lasttime = newtime;if (! event_is_persistent) {struct timeval tv;evutil_timerclear(&tv);tv.tv_sec = 2;event_add(timeout, &tv);}}intmain(int argc, char **argv){struct event timeout;struct timeval tv;struct event_base *base;int flags;#ifdef WIN32WORD wVersionRequested;WSADATA wsaData;wVersionRequested = MAKEWORD(2, 2);(void)WSAStartup(wVersionRequested, &wsaData);#endifif (argc == 2 && !strcmp(argv[1], "-p")) {event_is_persistent = 1;flags = EV_PERSIST;} else {event_is_persistent = 0;flags = 0;}/* Initalize the event library */base = event_base_new();/* Initalize one event */event_assign(&timeout, base, -1, flags, timeout_cb, (void*) &timeout);evutil_timerclear(&tv);tv.tv_sec = 2;event_add(&timeout, &tv);evutil_gettimeofday(&lasttime, NULL);event_base_dispatch(base);return (0);}

代码中有两种类型的timer:EV_PERSIST和非EV_PERSIST,前一种会一直触发,后一种只触发一次,可以通过在timer_cb中再增加一个timer事件,来模拟一直触发。                                             
0 0