linux下定时器实现
linux定时器:是指在每隔一段时间后就会进行一次相关操作,具有计时性的。
核心操作是如下方法
int setitimer(int which, const struct itimerval *restrict value, struct itimerval *restrict ovalue);
函数返回的是value指向的值,如果ovalue不为空时刚返回上一次的结果。
下面是例子一个。定义操作相关的头文件。
// // mtimer.h // ally // // Created by li yajie on 12/4/11. // Copyright (c) 2011 __MyCompanyName__. All rights reserved. // #ifndef ally_mtimer_h #define ally_mtimer_h /** * 定义一个消息处函数定义,由调用者去实现 * for example * switch (signo){ * // case SIGALRM: * // printf("Catch a signal -- SIGALRM \n"); * signal(SIGALRM, sigroutine); * break; * case SIGVTALRM: * printf("Catch a signal -- SIGVTALRM \n"); * signal(SIGVTALRM, sigroutine); * break; * } * return; */ typedef void (*msg_routine) (int signo) ; /** * 产生一个定时器 * param curTimeSec 程序运行多久秒后执行 * param curTimeUsec 程序运行多久毫秒后执行 * param loopSec 相隔多久秒后再次执行 * param loopUsec 相隔多久毫秒后再次执行 */ void mtimer(unsigned int curTimeSec,unsigned int curTimeUsec,unsigned int loopSec,unsigned int loopUsec); #endif
下面是实现部分:
// // mtimer.c // ally // // Created by li yajie on 12/4/11. // Copyright (c) 2011 __MyCompanyName__. All rights reserved. // #include <stdio .h> #include <string .h> #include <time .h> #include <sys /time.h> #include <unistd .h> #include "exception.h" #include "mtimer.h" //#include "types.h" /** * 时间结构体 */ struct itimerval tval; /** * 产生一个定时器 * param curTimeSec 程序运行多久秒后开始执行 * param curTimeUsec 程序运行多久毫秒后执行 * param loopSec 相隔多久秒后再次执行 * param loopUsec 相隔多久毫秒后再次执行 */ void mtimer(unsigned int curTimeSec,unsigned int curTimeUsec,unsigned int loopSec,unsigned int loopUsec) { int ret = 0; memset(&tval, 0, sizeof(tval)); tval.it_value.tv_sec = curTimeSec; tval.it_value.tv_usec = curTimeUsec; tval.it_interval.tv_sec = loopSec; tval.it_interval.tv_usec = loopUsec; ret = setitimer(ITIMER_REAL, &tval, NULL); if (ret) { printf("定时器创建失败\n"); // throw_my_exception(100, "定时器创建失败"); } }
但上面还有个问题,由于 setitimer() 不支持在同一进程中同时使用多次以支持多个定时器,因此,如果需要同时支持多个定时实例的话,需要由实现者来管理所有的实例。