mytime.h
#include<iostream>
#include<list>
class MyTimer {
public:
MyTimer();
~MyTimer();
typedef void(*f)();
struct TimerInfo {
int timerid;
long timerout;
long timerstart;
bool isvalid;
f task;
TimerInfo(int timerid, long timerout, long timerstart, f task) {
this->timerid = timerid;
this->timerout = timerout;
this->timerstart = timerstart;
this->task = task;
isvalid = true;
}
};
int AddTimerHandler(int timeout, f task);
void RemoveTimerHandler(const int timerid);
void updateTimer();
static int getTime();
int CreatTimerId();
public:
int Timerid;
long Time;
private:
std::list<TimerInfo> m_timerPool;
long m_lastid;
};
mytime.cpp
#include"mytime.h"
#include<Windows.h>
MyTimer::MyTimer() {
m_timerPool.clear();
}
MyTimer::~MyTimer() {
m_timerPool.clear();
}
int MyTimer::AddTimerHandler(int timeout, f task) {
int timeid = CreatTimerId();
m_timerPool.push_back(TimerInfo(timeid, timeout, getTime(), task));
return timeid;
}
void MyTimer::RemoveTimerHandler(const int timerid) {
auto it = m_timerPool.begin();
for (; it != m_timerPool.end(); it++) {
if (Timerid == it->timerid)
{
it->isvalid = false;
break;
}
else {
it++;
}
}
}
void MyTimer::updateTimer() {
auto it = m_timerPool.begin();
long currenttime = getTime();
for (; it != m_timerPool.end();) {
if (it->isvalid == false)
{
it = m_timerPool.erase(it);
continue;
}
if (currenttime >= (it->timerout + it->timerstart))
{
it->task();//执行定时器任务
it = m_timerPool.erase(it);
}
else {
it++;
}
}
}
int MyTimer::getTime() {
tm tms;
SYSTEMTIME sys;
GetLocalTime(&sys);
tms.tm_year = sys.wYear - 1900;
tms.tm_mon = sys.wMonth;
tms.tm_mday = sys.wDay;
tms.tm_hour = sys.wHour;
tms.tm_min = sys.wMinute;
tms.tm_sec = sys.wSecond;
tms.tm_isdst = -1;
long clock = mktime(&tms);
if (clock == -1)
{
std::cout << "Timer Error \n";
return -1;
}
else
clock = clock * 1000 + sys.wMilliseconds;
return clock;
}
int MyTimer::CreatTimerId() {
m_lastid = m_lastid % INT32_MAX;
if (m_lastid == 0)
m_lastid = 1;
m_lastid++;
return m_lastid;
}
main.cpp
#include <iostream>
#include"mytime.h"
#include<string>
#include <io.h>
#include <windows.h>
#include <fstream>
#include<vector>
using namespace std;
using namespace cv;
MyTimer timer;
long id1;
long id2;
//任务1
void task1() {
//任务1
id1 = timer.AddTimerHandler(1 * 1000, task1);//task1()重新加入定时器
}
//任务2
void task2() {
//任务2
id2 = timer.AddTimerHandler(1 * 1000, task2);//task2()重新加入定时器
}
int main()
{
id1 = timer.AddTimerHandler(1 * 1000, task1);
id2 = timer.AddTimerHandler(1 * 1000, task2);
while (1) {
timer.updateTimer();
}
}