仿DelayTime定时器

#include"iostream"
#include"windows.h"
#include "functional"
#include "time.h"
#include "math.h"
using namespace std;

class Ref
{

};



class DelayTime: public Ref
{
public:
	static DelayTime*create(float time, const function<void(void)> &f)
	{
		auto ss = new DelayTime;
		ss->func = f;
		ss->time = time*60;
		return ss;
	}

	function<void()> func;

	void run( )
	{
		func();
	}


	float time;
	float nowTime = 0;

};
int a = 0, b = 0;

class FrameManger :public Ref
{
public:
	FrameManger()
	{
		for (int i = 0; i < 100; i++)
		{
			queue[i] = nullptr;
		}
	}
	void addChild(DelayTime *pChild)
	{
		queue[count++] = pChild;
		
	}
	void Loop()
	{
		Sleep(rand()%5);
		for (int i = 0;i<count;i++)
		{
	
			if (queue[i] == nullptr)return;
			queue[i]->nowTime++;
			if (queue[i]->nowTime >= queue[i]->time)
			{
				 queue[i]->run();
				 cout << "    "<<clock()-a<<endl;
				 queue[i]->nowTime = 0;
				 a = clock();
			
			}
		}


	}
	 DelayTime* queue[100];
	 int count = 0;
};



int main()
{

	FrameManger*fr = new FrameManger;

	fr->addChild(DelayTime::create(1.0, [=]{cout << "callback_1"; }));
	fr->addChild(DelayTime::create(2.0, [=]{cout << "callback_2"; }));

	a = clock();


	LARGE_INTEGER nFreq;
	LARGE_INTEGER nLast;
	LARGE_INTEGER nNow;
	long long Interval;

	QueryPerformanceFrequency(&nFreq);
	Interval = (long long)(1/60.0 * nFreq.QuadPart);
	cout << "x=" << nFreq.QuadPart << endl;
	QueryPerformanceCounter(&nLast);
	while (1)
	{
		QueryPerformanceCounter(&nNow);
		if (nNow.QuadPart - nLast.QuadPart >Interval)//计算cpu频率计数差值
		{
			nLast.QuadPart = nNow.QuadPart;
			fr->Loop();
		}
		else
		{
			Sleep(0);
		}


	}
	






	system("pause");
	return 0;
}


你可能感兴趣的:(仿DelayTime定时器)