通过event类实现C++ Timer
event.hpp
#pragma once
#ifndef EVENT_HPP
#define EVENT_HPP
#pragma once
template <typename Handler>
class event
{
private:
Handler m_Handler;
protected:
virtual void add(const Handler value)
{
m_Handler = value;
}
virtual void remove(const Handler value)
{
if (value == m_Handler)
m_Handler = NULL;
}
public:
event()
{
m_Handler = NULL;
}
event& operator += (const Handler value)
{
add(value);
return *this;
}
event& operator -= (const Handler value)
{
remove(value);
return *this;
}
operator Handler()
{
return m_Handler;
}
};
typedef void(*EventHandler)();
#endif
timer.hpp
#pragma once
#ifndef TIMER_HPP
#define TIMER_HPP
#include <chrono>
#include <thread>
#include "event.hpp"
class Timer
{
private:
uint64_t interval;
unsigned defaultTime;
unsigned currentTime;
std::thread TimerThread;
public:
event<EventHandler> TimerTickEvent;
event<EventHandler> TimerDoneEvent;
public:
Timer() {
this->interval = 1000;
this->defaultTime = this->currentTime = 0;
}
Timer(uint64_t interval) {
this->interval = interval;
this->defaultTime = this->currentTime = 0;
}
Timer(uint64_t interval, unsigned ticks)
{
this->interval = interval;
this->defaultTime = this->currentTime = ticks;
}
void SetTime(unsigned ticks)
{
this->defaultTime = ticks;
}
void Start()
{
this->currentTime = this->defaultTime;
this->Runner();
}
private:
void Runner()
{
while (0 != this->currentTime)
{
--this->currentTime;
std::this_thread::sleep_for(std::chrono::milliseconds(this->interval));
if (NULL != TimerTickEvent)
((EventHandler)TimerTickEvent)();
}
if (NULL != TimerDoneEvent)
((EventHandler)TimerDoneEvent)();
}
};
#endif
main.cpp
#include <iostream>
#include "timer.hpp"
using namespace std;
void TimerTick();
void TimerDone();
int main()
{
Timer t(1000, 5);
t.TimerTickEvent += TimerTick;
t.TimerDoneEvent += TimerDone;
std::thread th = std::thread(&Timer::Start, &t);
th.join();
return 0;
}
void TimerTick()
{
cout << "Timer Tick!" << endl;
}
void TimerDone()
{
cout << "Timer Done!" << endl;
}