libeventでタイマー処理をする
libeventでタイマー処理をする方法について書きます。
まずは3秒後に指定の関数を呼ぶコードです。
#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; }
これをコンパイルして実行すると、3秒間待った後に"Hello"と表示して終了します。
次に、3秒ごとに指定の関数を実行してみます。
#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(); event_set(&ev, -1, EV_PERSIST, say_hello, NULL); evtimer_add(&ev, &tv); event_dispatch(); return 0; }
前のコードと違うのはevtimer_setがevent_setに変わっているところだけです。これをコンパイルして実行すると、3秒ごとに"Hello"と表示します。
タイマーを複数同時に動かすことも可能ですが、callbackで重い処理を動かしていると、その途中で呼ばれた別のcallbackは前の処理が終わるのを待つため、狙い通りのタイミングで動いてくれない点に注意が必要です。