Poco库Timer定时器

Poco库是一个很强大的C++库,其中常使用到的定时器类为Timer,下面就编写一个简单的定时器程序,具体说明参见注释’//'部分:

#include 
#include 
#include 
#include "Poco\Timer.h"

using namespace std;
using Poco::Timer;         // 使用Timer基类的成员
using Poco::TimerCallback; // 使用TimerCallback基类的成员

class StatTimer
{
public:
	Timer timer;
	TimerCallback callback;  // 套用模板,将StatTimer类关联起来
	bool end;

	StatTimer();
	bool start();
	void onTimer(Timer& t);
	void stop();
};

StatTimer::StatTimer() : timer(0, 2000), callback(*this, &StatTimer::onTimer), end(false)
{
}
// timer(0, 2000),第一个参数默认设置为0,2000代表时间间隔为2秒
// callback的第二个参数指定定时器需要做的具体事情

bool StatTimer::start()
{
	try
	{
		timer.start(callback);   // 启动定时器线程
		//started = true;
	}
	catch (...)
	{
		return false;
		end = true;
	}

	return true;
}

void StatTimer::onTimer(Timer&/*t*/)
{
	static size_t counter = 0;
	++counter;
	printf("\r%uA", counter);
	if (counter > 5)
		end = true;
}

void StatTimer::stop()
{
	timer.stop();  // 终止定时器线程
}

int main()
{
	cout << "Hello World!" << endl << endl;

	StatTimer *timer = new StatTimer();
	if (!timer->start())
	{
		cout << "Failed to start timer" << endl;;
	}

	while (1)
	{
		if (timer->end)
		{
			timer->stop();
			break;
		}		
	}

	cout << endl;
	system("pause");
	return 0;
}

读后有收获可以支付宝请作者喝咖啡:


Poco库Timer定时器_第1张图片

你可能感兴趣的:(C++,Windows)