#头文件CTime.h
#ifndef CTIMER_H
#define CTIMER_H
#include <windows.h>
typedef void (*TimerProcFunc)(void* userPtr);
class CTimer
{
public:
CTimer();
virtual ~CTimer();
int settimer(unsigned int uElaps, TimerProcFunc func, void *user);
void killtimer();
protected:
static unsigned __stdcall TimeThread(void * pParam);
private:
unsigned int m_uElaps;
void* m_pUser;
TimerProcFunc m_callBackFunc;
HANDLE m_hThread;
};
#endif
#源文件CTime.cpp
#include "stdafx.h"
#include "CTimer.h"
#include <time.h>
#include <process.h>
CTimer::CTimer()
: m_pUser(NULL)
, m_callBackFunc(NULL)
, m_hThread(NULL)
, m_uElaps(1)
{
}
CTimer::~CTimer()
{
if(m_hThread)
{
CloseHandle(m_hThread);
m_hThread = NULL;
}
}
unsigned __stdcall CTimer::TimeThread(void * pParam)
{
CTimer *pTimer = (CTimer*)pParam;
time_t t1, t2;
double Diff = 0;
/*获取系统当前时间*/
t1 = time(NULL);
while(1)
{
/*以秒为单位获取系统当前时间*/
t2 = time(NULL);
Diff = difftime(t2,t1);
if((int)Diff == pTimer->m_uElaps)
{
t1 = t2;
if (pTimer->m_callBackFunc)
{
pTimer->m_callBackFunc(pTimer->m_pUser);
}
}
}
return 0;
}
int CTimer::settimer(unsigned int uElaps, TimerProcFunc func, void *user)
{
if (m_hThread)
{
return -1;
}
m_uElaps = uElaps;
m_callBackFunc = func;
unsigned threadID;
m_hThread = (HANDLE)_beginthreadex(NULL, 0, CTimer::TimeThread, this, 0, &threadID);
if (m_hThread == 0)
{
return -1;
}
else
{
return 0;
}
}
void CTimer::killtimer()
{
if(m_hThread)
{
CloseHandle(m_hThread);
m_hThread = NULL;
}
}
#测试例子
#include "stdafx.h"
#include "CTimer.h"
void ProcFunc(void* userPtr)
{
printf("\nTime is here\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
CTimer myTimer;
myTimer.settimer(2, ProcFunc, NULL);
getchar();
return 0;
}