我有以下代码:
#include <stdio.h>
#include <sys/time.h>
#include <event.h>
void say_hello(int fd, short event, void *arg){
printf("Hellon");
}
int main(int argc, const char* argv[])
{
struct event ev;
struct timeval tv;
tv.tv_sec = 3;
tv.tv_usec = 0;
event_init();
evtimer_set(&ev,say_hello,NULL);
evtimer_add(&ev, &tv);
event_dispatch();
return 0;
}
问题是"你好"被打印一次,然后程序退出。。。
我希望它无限期地输出"你好"。
如何做到这一点?非常感谢,
只是为了澄清Basile的解决方案:
我也很困惑,直到我意识到本文中的">计时器"指的是单次计时器隔计时器;这需要libevent中的EV_PERSIST标志。
struct timeval time;
time.tv_sec = 1;
time.tv_usec = 0;
event_set(&my_event, 0, EV_PERSIST, my_function, NULL);
evtimer_add(&my_event, &time);
将main中的代码更改为读取
evtimer_set(&ev,say_hello,&ev);
并使您的say_hello函数
void say_hello(int fd, short event, void *arg){
struct event *ev = arg;
struct timeval tv;
printf("Hellon");
tv.tv_sec = 3;
tv.tv_usec = 0;
evtimer_add(ev, &tv);
}
以下是libevent2:的示例
#include <event2/event.h>
static int n_calls = 0;
void cb_func(evutil_socket_t fd, short what, void *arg)
{
struct event *me = arg;
printf("cb_func called %d times so far.n", ++n_calls);
if (n_calls > 100)
event_del(me);
}
void run(struct event_base *base)
{
struct timeval one_sec = { 1, 0 };
struct event *ev;
/* We're going to set up a repeating timer to get called called 100
times. */
ev = event_new(base, -1, EV_PERSIST, cb_func, event_self_cbarg());
event_add(ev, &one_sec);
event_base_dispatch(base);
}
您读过evtimer_set(3)手册页吗?请再读一遍。
您可能想要使用标志EV_PERSIST
或从say_hello
回调中调用evtimer_add
。
#include <stdio.h>
#include "ev.h"
static void timer_cback_caller(EV_P_ ev_timer* w, int revents)
{
const int new_timeout_in_ms = 1200; // new delay between timer ticks
printf("timer tickn");
w->repeat = new_timeout_in_ms / 1000.;
ev_timer_again(EV_A_ w);
}
int main()
{
struct ev_loop *loop = ev_default_loop(0);
ev_timer timer;
const int start_delay_in_ms = 1000; // delay before first timer tick
const int timeout_in_ms = 1500; // delay between every timer tick
ev_timer_init(&timer, timer_cback_caller, start_delay_in_ms/1000., timeout_in_ms/1000.);
ev_timer_start(loop, &timer);
ev_run(loop, 0); // will never return
return 0;
}
libev文档中的更多示例