先打個卡,下一篇將把各個系統上的定時器code總結一下。包括秒級、微秒級。
本篇爲根據工程需求,在Linux系統上寫的一個簡單的定時器。
#include <sys/time.h>
#include <string>
class Timer
{
private:
/* data */
timeval T_starttime;
timeval T_pausetime;
bool T_isstop;
time_t T_timep;
struct tm *T_p;
public:
double d_interval;
public:
Timer();
~Timer();
bool isStop();
void Start();
void Stop();
bool IsAlarm(double);
char* TimeStamp();
};
Timer::Timer()
{
T_isstop = true;
}
Timer::~Timer()
{
}
bool Timer::isStop()
{
if(T_isstop) return true;
else return false;
}
void Timer::Start()
{
if(T_isstop)
{
gettimeofday(&T_starttime,0);
T_isstop = false;
}
else
{
printf("Warning: Already started!");
return;
}
}
void Timer::Stop()
{
if(T_isstop)
{
printf("Warning:Already Stopped!");
return;
}
else
{
T_isstop = true;
return;
}
}
bool Timer::IsAlarm(double interval)
{
gettimeofday(&T_pausetime,0);
double timeuse=1000000*(T_pausetime.tv_sec-T_starttime.tv_sec)+ \
T_pausetime.tv_usec-T_starttime.tv_usec;
timeuse /=1000000;
// printf("timeuse:%f\n",timeuse);
if(timeuse>=interval)
{
T_isstop = true;
Start();
return true;
}
else
{
return false;
}
}
char* Timer::TimeStamp()
{
time(&T_timep);
T_p=localtime(&T_timep);
std::string s_time;
s_time = std::to_string(T_p->tm_hour) + "-"+std::to_string(T_p->tm_min) \
+ "-" + std::to_string(T_p->tm_sec);
char *p_time=(char*)s_time.c_str();
return p_time;
}