libevent:使计时器持久化

时间:2012-11-27 13:27:35

标签: c timer libevent

我有以下代码:

#include <stdio.h>
#include <sys/time.h>
#include <event.h>

void say_hello(int fd, short event, void *arg){
        printf("Hello\n");
}

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;
}

问题是&#34;你好&#34;打印一次然后程序退出...

我希望它输出&#34;你好&#34;下去。

怎么做?非常感谢,

5 个答案:

答案 0 :(得分:7)

只是为了澄清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);

答案 1 :(得分:4)

将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("Hello\n");
    tv.tv_sec = 3;
    tv.tv_usec = 0;

    evtimer_add(ev, &tv);
}

答案 2 :(得分:2)

这是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);
}

答案 3 :(得分:1)

您是否阅读了evtimer_set(3)手册页?请再读一遍。

您可能希望使用EV_PERSIST标记或从evtimer_add回调中拨打say_hello

答案 4 :(得分:0)

#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 tick\n");

    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 documentation

中的更多示例