全部博文(66)
分类:
2012-11-29 09:09:19
原文地址:LINUX RTC机制实现计时器类 作者:chumojing
CTimer.h:
/*
* CTimer.h
*
* Created on: 2009-7-13
* Author: DEAN
*/
//////////////////////////////////////////////////////////////
// This class provide a timer to finish some works.
// Call StartTimer() to enable it and call StopTimer() to stop
// it. The work you want to do should be written on OnTimer()
// function. Call SetInterval(x) to set every x second to call
// OnTimer() once.
//////////////////////////////////////////////////////////////
#ifndef CTIMER_H_
#define CTIMER_H_
#include
#include
#include
#include
class CTimer
{
private:
static CTimer *g_singleinstance;
long m_second, m_counter;
unsigned long m_data;
int m_rtcfd;
pthread_t thread_timer;
static void *thread_stub(void *p)
{
(static_cast
}
void *thread_proc();
void OnTimer();
protected:
CTimer();
public:
virtual ~CTimer();
static CTimer *Instance();
void SetInterval(long second);
void StartTimer();
void StopTimer();
};
#endif /* CTIMER_H_ */
CTimer.cpp:
/*
* CTimer.cpp
*
* Created on: 2009-7-13
* Author: dean
*/
#include "Timer.h"
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
CTimer *CTimer::g_singleinstance = 0;
CTimer::CTimer():
m_second(2), m_counter(0)
{
//Init the rtc
m_rtcfd = open("/dev/rtc", O_RDONLY);
if(m_rtcfd < 0)
{
cout<<"TimerWarning: open /dev/rtc error..."<
}
//设定频率 2Hz
if(ioctl(m_rtcfd, RTC_IRQP_SET, 2) < 0)
{
cout<<"TimerWarning: Set rtc request failed..."<
return;
}
pthread_create(&thread_timer, NULL, thread_stub, this);
}
//////////////////////////private methods//////////////////////////
void *CTimer::thread_proc()
{
int nfds;
while(true)
{
read(m_rtcfd,&m_data,sizeof(unsigned long));
++m_counter;
if (m_counter >= m_second)
{
OnTimer();
m_counter = 0;
}
pthread_testcancel();
}
}
void CTimer::OnTimer()
{
cout<<"Timer...."<
//////////////////////////public methods//////////////////////////
CTimer::~CTimer()
{
pthread_cancel(thread_timer);
pthread_join(thread_timer, NULL);
close(m_rtcfd);
}
CTimer *CTimer::Instance()
{
if (g_singleinstance == 0)
g_singleinstance = new CTimer;
return g_singleinstance;
}
void CTimer::SetInterval(long second)
{
m_second = second * 2;
}
void CTimer::StartTimer()
{
if (!(m_rtcfd > 0))
{
cout<<"TimerWarning: rtcfd < 0...Start failed..."<
}
if(ioctl(m_rtcfd, RTC_PIE_ON, 0) < 0)
{
cout<<"TimerWarning: ioctl(RTC_PIE_ON) failed..."<
return;
}
m_counter = 0;
}
void CTimer::StopTimer()
{
if (!(m_rtcfd > 0))
{
cout<<"TimerWarning: rtcfd < 0...Stop failed..."<
}
if(ioctl(m_rtcfd, RTC_PIE_OFF, 0) < 0)
{
cout<<"TimerWarning: ioctl(RTC_PIE_ON) failed..."<
return;
}
}