linux定时器接口timerfd案例

        timerfd是linux为用户程序提供的一个定时器接口。这个接口基于文件描述符,通过文件描述符的可读事件进行超时通知,所以能够被用于select、poll及epoll的应用场景。

         包含头文件:#include

        创建一个定时器描述符timerfd

                int timerfd_create(int clockid, int flags)

        用来启动或关闭有fd指定的定时器

                int timerfd_settime(int fd, int flags, const struct itimerspec *new_value, struct itimerspec *old_value);

        此函数用于获得定时器距离下次超时还剩下的时间

                int timerfd_gettime(int fd, struct itimerspec *curr_value);

        函数功能、参数这里都不做过多赘述,网上非常多,直接上测试代码,有助于理解,代码如下:

#include  
#include  
#include  
#include  
#include  
#include 
#include  
#include 

using namespace std;

void WriteLog()
{
    //获取系统时间戳
	time_t timeReal;
	time(&timeReal);
	timeReal = timeReal + 8*3600;
	tm* t = gmtime(&timeReal);
	printf("%d-%02d-%02d %02d:%02d:%02d\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); 
}

void addfd(int epollfd, int fd)
{
	struct epoll_event event;
	event.data.fd = fd;
	event.events  = EPOLLIN;
	
	epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event );
}

int create_timer(int epfd) {
	int timerfd; 
    struct itimerspec timerValue; 

    /* set timerfd */ 
    timerfd = timerfd_create(CLOCK_MONOTONIC, 0); 
    if (timerfd < 0) {
		printf("failed to create timer fd\n"); 
		exit(1); 
    } 
    bzero(&timerValue, sizeof(timerValue)); 

    timerValue.it_value.tv_sec = 2; 
    timerValue.it_value.tv_nsec = 0; 
    timerValue.it_interval.tv_sec = 4; 
    timerValue.it_interval.tv_nsec = 0; 

    /* set events */ 
    addfd(epfd, timerfd);

    /* start timer */ 
    if (timerfd_settime(timerfd, 0, &timerValue, NULL) < 0){ 
		printf("could not start timer\n"); 
		exit(1); 
    }
	
	return timerfd;
}

int main() 
{
    struct epoll_event newEvents; 
	struct itimerspec timerValue;
    
    int epollfd = epoll_create1(0); 
	
	int timerfd = create_timer(epollfd);

	int i = 0;
	WriteLog();
    while (true) {
		int numEvents = epoll_wait(epollfd, &newEvents, 1, -1);
		WriteLog();
		
		if (numEvents > 0) { 
			int timersElapsed = 0; 
			
			read(newEvents.data.fd, &timersElapsed, 8);
			printf("timers elapsed: %d\n", timersElapsed);
			
			if(i++ == 3) {
				timerValue.it_value = {0, 0};
				timerValue.it_interval = {1, 0};
				timerfd_settime(timerfd, 0, &timerValue, NULL);
				printf("设置关闭定时器!!!\n");
			}
		}
    } 

    return 0;
} 

        执行结果:

linux定时器接口timerfd案例_第1张图片

你可能感兴趣的:(服务器,c++,定时器,timerfd)