【開源Libevent篇章二】定時器的運用

一、 示例介紹


每隔一秒循環打印信息“Come On!”


二、 代碼編譯和運行結果


1. 編譯命令: g++ -o timer timer.cpp -levent

2. 運行結果:

[root@f8s test_timer]# ./timer
Come On!
Come On!
Come On!
Come On!
Come On!


三、 代碼展示


/*
 * libevent定時器事件的運用示例: 每隔一秒打印Come On!
 */
#include <stdio.h>  
#include <iostream>  
  
// libevent頭文件  
#include <event.h>  
using namespace std;  
  
// 定時事件回調函數  
void onTime(int sock, short event, void *arg)  
{  
    cout << "Come On!" << endl;  
  
    struct timeval tv;  
    tv.tv_sec = 1;  
    tv.tv_usec = 0;  
    // 重新添加定時事件(定時事件觸發後默認自動刪除)  
    event_add((struct event*)arg, &tv);  
}  
  
int main()  
{  
    // 初始化  
    event_init();  
  
    struct event evTime;  
    // 設置定時事件  
    evtimer_set(&evTime, onTime, &evTime);  
  
    struct timeval tv;  
    tv.tv_sec = 1;  
    tv.tv_usec = 0;  
    // 添加定時事件  
    event_add(&evTime, &tv);  
  
    // 事件循環  
    event_dispatch();  
  
    return 0;  
}  


四、 編譯問題


1. 問題現象

./timer: error while loading shared libraries: libevent-1.4.so.2: cannot open shared object file: No such file or directory

2. 解決辦法

ln -s /usr/local/lib/libevent-1.4.so.2 /usr/lib/libevent-1.4.so.2   


五、 代碼下載


點我


發佈了79 篇原創文章 · 獲贊 5 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章