C++ 定时器任务类实现
#ifndef __TIMERTASK_H_ #define __TIMERTASK_H_ /* 定时器任务基类 */ #include "asr_taskinterface.h" #include "comontype.h" class BaseTimerTask { public: BaseTimerTask():m_uiTvSec(0),m_uiTvUsec(0){} virtual ~BaseTimerTask(){} public: //设置定时器间隔 void setTimer(UINT uiTvSec,UINT uiTvUsec = 0); //启动定时器 void startTimer(UINT uiTvSec,UINT uiTvUsec = 0); //周期性任务 virtual void intervalTask() = 0; private: UINT m_uiTvSec; //秒 UINT m_uiTvUsec; //微秒 }; #endif
#include "timertask.h" #include <sys/select.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <errno.h> /******************************************************** BaseTimerTask *********************************************************/ /******************************************************** Func Name: setTimer Date Created: 2018-7-30 Description: 设置定时器 Input: uiTvSec:设置间隔多少秒 uiTvUsec:设置间隔多少微秒 Output: Return: Caution: *********************************************************/ void BaseTimerTask::setTimer(UINT uiTvSec,UINT uiTvUsec) { m_uiTvSec = uiTvSec; m_uiTvUsec = uiTvUsec; } /******************************************************** Func Name: setTimer Date Created: 2018-7-30 Description: 开启定时器 Input: uiTvSec:设置间隔多少秒 uiTvUsec:设置间隔多少微秒 Output: Return: Caution: *********************************************************/ void BaseTimerTask::startTimer(UINT uiTvSec,UINT uiTvUsec) { int infds = 0; struct timeval stTimeval; m_uiTvSec = uiTvSec; m_uiTvUsec = uiTvUsec; do { stTimeval.tv_sec = (long)m_uiTvSec; stTimeval.tv_usec = (long)m_uiTvUsec; //select()每次返回后都会清空struct timeval参数 infds = select(0, NULL, NULL, NULL, &stTimeval); //执行任务 intervalTask(); } while ((0 == infds) || (infds < 0 && EINTR == errno)); }
#ifndef __TESTTIMER_H_ #define __TESTTIMER_H_ /* 测试定时器任务类 */ #include "timertask.h" class CPrintTimer:public BaseTimerTask { public: virtual void intervalTask(); }; #endif
#include <iostream> #include "testtimer.h" /******************************************************** CPrintTimer *********************************************************/ /******************************************************** Func Name: intervalTask Date Created: 2018-7-30 Description: 执行任务 Input: Output: Return: Caution: *********************************************************/ void CPrintTimer::intervalTask() { std::cout << "praise chaos" << std::endl; }