网络库Libevent学习之定时器的实现方法

定时器是一种特殊类型的时间间隔测量的时钟,定时器发出提示代表时间间隔已过期。下面我们就用网络库Libevent实现简单的定时器功能:每5秒执行一次回调函数,打印当前时间。

#include <stdio.h>
#include <time.h>
#include <event2/event.h>
#include <event2/event_struct.h>

void timeout_cb(evutil_socket_t fd, short event, void *arg)
{
    time_t t = time(NULL);
    printf("%s", ctime(&t));
}
 
int main(void)
{
    struct event timeout;
    struct event_base *base;
    struct timeval tv;
 
    base = event_base_new();
    event_assign(&timeout, base, -1, EV_PERSIST, timeout_cb, NULL);
 
    evutil_timerclear(&tv);
    tv.tv_sec = 5;
    tv.tv_usec = 0;
 
    event_add(&timeout, &tv);
    event_base_dispatch(base);
 
    return 0;
}
[ycxie@fedora Workspace]$ gcc -o libevent_timer -levent -Wall libevent_timer.c
[ycxie@fedora Workspace]$ ./libevent_timer
Tue Jul 17 12:32:14 2018
Tue Jul 17 12:32:19 2018
Tue Jul 17 12:32:24 2018
Tue Jul 17 12:32:29 2018
Tue Jul 17 12:32:34 2018

为使用方便,libevent提供了一些以evtimer_开头的宏,用于替代event_*调用来操作纯超时事件。使用这些宏能改进代码的清晰性。

#include <stdio.h>
#include <time.h>
#include <event2/event.h>
#include <event2/event_struct.h>

void timeout_cb(evutil_socket_t fd, short event, void *arg)
{
	time_t t = time(NULL);
	printf("%s", ctime(&t));
	
	struct timeval tv;
	evutil_timerclear(&tv);
	tv.tv_sec = 5;
	tv.tv_usec = 0;

	struct event *timeout = arg;
	evtimer_add(timeout, &tv);
}

int main(void)
{
	struct event timeout;
	struct event_base *base;
	struct timeval tv;

	base = event_base_new();
	evtimer_assign(&timeout, base, timeout_cb, &timeout);

	evutil_timerclear(&tv);
	tv.tv_sec = 5;
	tv.tv_usec = 0;

	evtimer_add(&timeout, &tv);
	event_base_dispatch(base);

	return 0;
}
[ycxie@fedora Workspace]$ gcc -o libevent_timer -levent -Wall libevent_timer.c
[ycxie@fedora Workspace]$ ./libevent_timer
Tue Jul 17 13:01:57 2018
Tue Jul 17 13:02:02 2018
Tue Jul 17 13:02:07 2018
Tue Jul 17 13:02:12 2018
Tue Jul 17 13:02:17 2018

Leave a Reply

Your email address will not be published. Required fields are marked *