这个设计每调用一次就会重新注册,欢迎交流
#include <iostream>
#include <map>
#include <vector>
#include <time.h>
#include <windows.h>
#include <stdio.h>
using namespace std;
struct tagTime
{
long long llStarTime;
int iCount;
int iSpace;
int iParam;
};
map<long long, vector<tagTime>> TimeList;
/*利用map如果key是整形,会自动从小到大排序,
我们可以把定时器先到期的key更小
由于相同时间到期的会重复,所以还得去重
那可以用二维结构,map<key,vector>,刚好vector是pushback有序的
*/
bool RegTimer(tagTime &Timer)
{
//cout<<Timer.llStarTime<<endl;
map<long long, vector<tagTime>>::iterator It = TimeList.find(Timer.llStarTime);
if(It == TimeList.end())
{
vector<tagTime> vTimelist;
vTimelist.push_back(Timer);
TimeList[Timer.llStarTime] = vTimelist;
}
else
{
It->second.push_back(Timer);
}
return true;
}
void UpdateTimer()
{
if(TimeList.size() <= 0)
return;
map<long long, vector<tagTime>>::iterator It = TimeList.begin();
if(time(NULL) < It->first)
{
//cout<<"000"<<time(NULL) <<" "<< It->first<<endl;
return;
}
vector<tagTime> *vTimeList = &(It->second);
if(vTimeList->size() <= 0)
{
//cout<<"111"<<endl;
return;
}
vector<tagTime>::iterator vIt = vTimeList->begin();
for(; vIt != vTimeList->end(); vIt++)
{
tagTime Timer = *vIt;
cout<<Timer.iCount<<" "<<Timer.iParam<<endl;
Timer.iCount--;
Timer.llStarTime = Timer.llStarTime + Timer.iSpace;
if(0 < Timer.iCount)
{
RegTimer(Timer);
}
}
vTimeList->clear();
TimeList.erase(It);
}
void main()
{
tagTime Timer;
Timer.iCount = 10;
Timer.iParam = 5201314;
Timer.iSpace = 1;
Timer.llStarTime = time(NULL);
RegTimer(Timer);
Timer.iParam = 141414;
Timer.iSpace = 2;
RegTimer(Timer);
while (true)
{
UpdateTimer();
Sleep(100);
}
system("pause");
}