4

我有以下代码:

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

问题是“你好”被打印一次然后程序退出......

我希望它无限期地输出“你好”。

这个怎么做?提前谢谢了,

4

5 回答 5

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);
于 2013-07-22T20:57:57.023 回答
5

将 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);
}
于 2013-08-24T00:44:07.663 回答
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);
}
于 2014-10-06T17:23:10.200 回答
1

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

您可能想使用标志EV_PERSISTevtimer_add从您的say_hello回调中调用。

于 2012-11-27T13:32:21.520 回答
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 文档中的更多示例

于 2018-09-21T09:02:15.543 回答