epoll timer实现定时任务

static int start_histroy_timer(){

    int timerfd = timerfd_create(CLOCK_MONOTONIC,TFD_NONBLOCK);
    if(timerfd ==-1){
        log_printfln(LOG_INFO," histroy_data timerfd_create fail");
        return -1;
    }

    struct itimerspec new_value = {};
    new_value.it_value.tv_sec = 3;    //第一次3s到期
    new_value.it_value.tv_nsec = 0;

    // new_value.it_interval.tv_sec = 10 * 60;  //后续周期是10 min cycle
    new_value.it_interval.tv_sec = 5;  //后续周期是10 min cycle
    new_value.it_interval.tv_nsec = 0;

    if(timerfd_settime(timerfd,0,&new_value,NULL)==-1){
        log_printfln(LOG_INFO," histroy_data timerfd_settime fail");
        return -1;
    }
    log_printfln(LOG_INFO, "histroy_data timer started");
    int epollfd = epoll_create1(EPOLL_CLOEXEC);
    if(epollfd == -1){
        log_printfln(LOG_INFO, "histroy_data epoll_create1 fail");
        return -1;
    }

    struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = timerfd;

    epoll_ctl(epollfd,EPOLL_CTL_ADD,timerfd,&ev);

    const int maxEvents = 1;  //也可以设置为1
    struct epoll_event events[maxEvents];

    while(1){
        int nfd = epoll_wait(epollfd,events,maxEvents,-1);
        if(nfd>0){
            for(int i=0;i<maxEvents;i++){
                if(events[i].data.fd == timerfd){
                    uint64_t exp = 0;
                    int ret = read(timerfd,&exp,sizeof(uint64_t));  //为什么会有这儿块?????,如果不把数据读取出来,就不会10分钟采集一次,会毫秒级别任务,跟我们想象的不一致
                    if(ret != sizeof(uint64_t)){
                        log_printfln(LOG_INFO,"read histroy_data timerfd");
                        return -1;
                    }
                    collect_rtu_data();   // 除第一次1s外,每5s打印一次
                }
            }
        }
    }
    close(epollfd); //关闭epllfd
    close(timerfd); //关闭timerfd
}