定時器是線程擴展,預定未來時刻觸發信號。關注點:精度(平台相關)、可重複觸發、單定時器單時間(多時間需多定時器)。
Poco::Timer m_timer;。void onTimer(Timer&)。setStartInterval(ms) 首次延遲,setPeriodicInterval(ms) 週期;或構造 Timer(start, period)。Poco::TimerCallback<Class> cb(*this, &Class::onTimer);。m_timer.start(cb, threadPool);。m_timer.stop();。
#include <Poco/Timer.h>
#include <Poco/Thread.h>
#include <Poco/Stopwatch.h>
#include <iostream>
using Poco::Timer; using Poco::TimerCallback; using Poco::Thread; using Poco::Stopwatch;
class TimerExample {
Stopwatch _sw;
public:
TimerExample() { _sw.start(); }
void onTimer(Timer& timer) {
std::cout << "Callback after " << _sw.elapsed()/1000 << " ms." << std::endl;
}
};
int main() {
TimerExample ex;
Timer timer(2500, 500); // 2.5s 首次,500ms 週期
timer.start(TimerCallback<TimerExample>(ex, &TimerExample::onTimer));
Thread::sleep(5000); // 主線程等待
// timer.stop();
return 0;
}
輸出:啟動 2.5s 後,每 0.5s 觸發一次回調。