libevent: make timer persistent

Eamorr picture Eamorr · Nov 27, 2012 · Viewed 8.7k times · Source

I have the following code:

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

Problem is "hello" gets printed once and then the program exits...

I want it to output "hello" indefinitely.

How to do this? Many thanks in advance,

Answer

seo picture seo · Jul 22, 2013

Just to clarify Basile's solution:

I was confused as well until I realized that "timer" in this context refers to a single shot timer. What we need is an interval timer; which requires the EV_PERSIST flag in libevent.

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