定時器類聲明文件
//cMyTimer.h
#pragma once
#include "string"
#include "list"
using namespace std;
struct stTimer
{
unsigned timeElapce; //定時器間隔運行時間
unsigned timeCreate; //定時器創建時間
unsigned timeLastRun; //定時器上次執行時間
unsigned id; //定時器ID號
int iParam; //預留參數
string strParam; //預留參數
bool bDel; //是否已被刪除
stTimer()
{
timeCreate = 0;
timeLastRun = 0;
id = -1;
iParam = 0;
bDel = false;
}
};
typedef list<stTimer> stTimerList;
typedef list<stTimer>::iterator itTimerList;
class cMyTimer
{
public:
cMyTimer();
virtual ~cMyTimer();
//添加定時器
void AddTimer(unsigned timerId, unsigned timeMs,int param = 0,
char* p=NULL);
//刪除定時器
void DeleteTimer(int id);
//定時器處理
virtual int OnTimer(int id,int iParam,string str) = 0;
//檢測定時器運行
bool TimerRun();
//清除所有定時器
void ClearTimer();
//定時檢測刪除定時器
void CheckDelTimer();
private:
stTimerList m_timerList; //定時器列表
};
定時器類定義文件
//cMyTimer.cpp
#include "stdafx.h"
#include "cMyTimer.h"
#include "windows.h"
#include "process.h"
cMyTimer::cMyTimer()
{
}
cMyTimer::~cMyTimer()
{
ClearTimer();
}
void cMyTimer::ClearTimer()
{
for (itTimerList it = m_timerList.begin();it != m_timerList.end();++it)
{
it->bDel = true;
}
}
void CheckTimerRun(void* p)
{
cMyTimer* pTimer = (cMyTimer*)p;
if (pTimer == NULL)
{
return;
}
while(1)
{
pTimer->CheckDelTimer();
//檢測是否有定時器要運行
if(!pTimer->TimerRun())
{
_endthread();
}
Sleep(20);
}
}
//添加定時器
void cMyTimer::AddTimer(unsigned timerId,unsigned timeMs,int param,char* p)
{
if (timeMs == 0)
{
return;
}
stTimer stTimerTemp;
stTimerTemp.bDel = false;
stTimerTemp.id = timerId;
stTimerTemp.iParam = param;
if (p != NULL)
{
stTimerTemp.strParam = p;
}
unsigned timeNow = GetTickCount();
stTimerTemp.timeCreate = timeNow;
stTimerTemp.timeLastRun = timeNow;
stTimerTemp.timeElapce = timeMs;
m_timerList.push_back(stTimerTemp);
if (m_timerList.size() == 1)
{
//說明此時是第一個定時器
_beginthread(CheckTimerRun,0,this);
}
}
//刪除定時器
void cMyTimer::DeleteTimer(int id)
{
for (itTimerList it = m_timerList.begin();it != m_timerList.end();++it)
{
if (it->id == id)
{
it->bDel = true;
return;
}
}
}
//定時器處理
//int cMyTimer::OnTimer(int id,int iParam,string str)
//{
// return 1;
//}
//定時檢測刪除定時器
void cMyTimer::CheckDelTimer()
{
for (itTimerList it = m_timerList.begin();it != m_timerList.end();)
{
if (it->bDel)
{
m_timerList.erase(it);
it = m_timerList.begin();
continue;
}
++it;
}
}
bool cMyTimer::TimerRun()
{
if (m_timerList.size() == 0)
{
return false;
}
unsigned timeNow = GetTickCount();
for (itTimerList it = m_timerList.begin();it != m_timerList.end();++it)
{
if (timeNow>=it->timeLastRun + it->timeElapce)
{
it->timeLastRun = timeNow;
if(OnTimer(it->id,it->iParam,it->strParam) == 0)
{
//刪除定時器
it->bDel = true;
}
continue;
}
}
return true;
}