自己写的一个多进程的定时器类方便使用,放在bolg里

来源:互联网 发布:淘宝erp系统 编辑:程序博客网 时间:2024/05/16 12:01

//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;
}

0 0
原创粉丝点击