Poco库是一个很强大的C++库,其中常使用到的定时器类为Timer,下面就编写一个简单的定时器程序,具体说明参见注释’//'部分:
#include <stdio.h>
#include <iostream>
#include <string>
#include "Poco\Timer.h"
using namespace std;
using Poco::Timer; // 使用Timer基类的成员
using Poco::TimerCallback; // 使用TimerCallback基类的成员
class StatTimer
{
public:
Timer timer;
TimerCallback<StatTimer> 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;
p