C++ Timer类实现

通过event类实现C++ Timer

event类参考

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;
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值