c++定时器实现

随便写了一个简单定时器

#pragma once
#include <Windows.h>
#include <list>
#include <iostream>
using namespace std;

struct tTIMER
{
	unsigned nID;			//定时器ID
	unsigned nTimeElapce;	//定时器运行间隔(ms)
	unsigned nTimeCreate;	//定时器创建时间
	unsigned nTimeLastRun;	//定时器上次运行时间
	bool bStatus;			//定时器状态,true启用,false停用
	tTIMER()
	{
		nID = -1;
		nTimeCreate = 0;
		nTimeElapce = 0;
		nTimeLastRun = 0;
		bStatus = true;
	}

	bool operator < (const tTIMER &timer) const
	{
		return this->nTimeElapce + this->nTimeLastRun < timer.nTimeElapce + timer.nTimeLastRun;
	}
};

typedef list<tTIMER> listTimer;
typedef list<tTIMER>::iterator itListTimer;

class CTimer
{
public:
	CTimer();
	~CTimer();

public:
	//设置定时器
	virtual void SetTimer(unsigned nTimerID, unsigned nTimerMS, int nParam = 0, char* p = NULL);

	//删除定时器
	virtual void KillTimer(unsigned nTimeerID);

	//定时器处理函数
	virtual int OnTimer(int nID) = 0;

protected:
	static DWORD WINAPI TimerThread(LPVOID lpParam);
private:
	listTimer m_ltTimeList;		//定时器列表
	bool m_bRun;
};

#include "Timer.h"
#include <process.h>


CTimer::CTimer():
m_bRun(true)
{
}


CTimer::~CTimer()
{
	m_bRun = false;
	m_ltTimeList.clear();
}

void CTimer::SetTimer(unsigned nTimerID, unsigned nTimerMS, int nParam /* = 0 */, char* p /* = NULL */)
{
	if (nTimerMS == 0)
	{
		return;
	}
	tTIMER tTimer;
	tTimer.bStatus = true;
	tTimer.nID = nTimerID;
	unsigned nTimeNow = GetTickCount();
	tTimer.nTimeCreate = nTimeNow;
	tTimer.nTimeLastRun = nTimeNow;
	tTimer.nTimeElapce = nTimerMS;
	m_ltTimeList.push_back(tTimer);
	if (m_ltTimeList.size() == 1)
	{
		m_bRun = true;
		HANDLE handle = CreateThread(NULL, 0, TimerThread, this, 0, 0);
		CloseHandle(handle);
	}
}

void CTimer::KillTimer(unsigned nTimeerID)
{
	for (auto it = m_ltTimeList.begin(); it != m_ltTimeList.end(); ++it)
	{
		if (nTimeerID == it->nID)
		{
			it->bStatus = false;
			break;
		}
	}
}

DWORD WINAPI CTimer::TimerThread(LPVOID lpParam)
{
	CTimer *pTimer = (CTimer*)lpParam;
	while (pTimer->m_bRun)
	{
		if (pTimer->m_ltTimeList.size() < 1)
		{
			break;
		}
		//定时器排序
		pTimer->m_ltTimeList.sort();
		unsigned nTimeNow = GetTickCount();
		for (itListTimer it = pTimer->m_ltTimeList.begin(); it != pTimer->m_ltTimeList.end(); ++it)
		{
			if (!it->bStatus)
			{
				it = pTimer->m_ltTimeList.erase(it);
				continue;
			}
			if (nTimeNow >= it->nTimeLastRun + it->nTimeElapce)
			{
				it->nTimeLastRun = nTimeNow;
				pTimer->OnTimer(it->nID);
			}
			else
			{
				break;
			}
		}
		Sleep(0);
	}
	return 0;
}

int CTimer::OnTimer(int nID)
{
	return 0;
}


猜你喜欢

转载自blog.csdn.net/china_zyl/article/details/59491795