c++ 定時器實現

1. setitimer方法

nginx 實現, 在這段代碼中,定義了itimerval的數據結構,並設置這個數據結構的值,從而定時器的間隔時間,settimer的函數第一個參數表示經過timer就會觸發sigalarm事件, 然後註冊了信號sigalarm的事件,從而觸發定時器

signal(SIGALRM, printMsg);  
void printMsg(int num) {  

  printf("%s","Hello World!!\n");  

}  

struct itimerval  itv;
itv.it_interval.tv_sec = ngx_timer_resolution / 1000;
itv.it_interval.tv_usec = (ngx_timer_resolution % 1000) * 1000
itv.it_value.tv_sec = ngx_timer_resolution / 1000;
itv.it_value.tv_usec = (ngx_timer_resolution % 1000 ) * 1000;

  if (setitimer(ITIMER_REAL, &itv, NULL) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setitimer() failed");
        }

2. pthread_mutex_timedlock
在dtc的agent實現中,先創建一個線程,然後在線程中用如下的函數來阻塞,從而達到定時器的目的。pthread_mutex_timedlock指的是阻塞願意等待的時間ts

pthread_mutex_trylock(&wakeLock)
while(pthread_mutex_timedlock(&wakeLock, &ts) != 0)
{
    //DoSth
}

3. epoll_wait實現

可以設置epoll_wait的timeout從而達到定時器,epoll等待timeout秒之後就執行後面的程序

int epoll_wait(int efd, struct epoll_event *event, int maxeevents, int timeout)
//efd 由epoll_create創建的fd
//timeout 爲一次監聽的間隔
//當有事件觸發 返回int 表示事件個數,event裏存儲的是觸發的事件

模擬定時器寫的一個代碼

#include<stdio.h>
#include<sys/epoll.h>
#include <sys/time.h>
#include<time.h>
#include<signal.h>
#include <stdlib.h>
#include <unistd.h>

#define MAX_EVENTS 100
void printMsg(int num) {

        time_t t = time(NULL);
        struct tm *tt = localtime(&t);
        printf("%d,%d,%d\n", tt->tm_hour, tt->tm_min , tt->tm_sec);
        printf("%s","Hello World!!\n");

}
int main()
{
        struct epoll_event events[MAX_EVENTS];
        int  ep;
        int nfds;
        while(0==0)
{
        ep = epoll_create(100);
        signal(SIGALRM, printMsg);
        struct itimerval itv;
        itv.it_interval.tv_sec = 10 ;
        itv.it_interval.tv_usec = 0 ;
        //itv.it_interval.tv_usec = (ngx_timer_resolution % 1000) * 1000;
        itv.it_value.tv_sec = 10;
        itv.it_value.tv_usec = 10;
        //itv.it_value.tv_usec = (ngx_timer_resolution % 1000 ) * 1000;
        setitimer(ITIMER_REAL, &itv, NULL);
        nfds = epoll_wait(ep, events, MAX_EVENTS, -1);
        printf("%d events occur\n", nfds);
}
}
發佈了46 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章