2
我想在最後一個異步事件發生後n秒後延遲一次特定操作。因此,如果連續事件在n秒內出現,則具體操作被延遲(deadline_timer重新啓動)。使用boost的延遲操作:: deadline_timer
我修改了從boost deadline_timer issue開始的定時器類,爲了簡單起見,事件是同步生成的。運行代碼,我希望是這樣的:
1 second(s)
2 second(s)
3 second(s)
4 second(s)
5 second(s)
action <--- it should appear after 10 seconds after the last event
,但我得到
1 second(s)
2 second(s)
action
3 second(s)
action
4 second(s)
action
5 second(s)
action
action
爲什麼會出現這種情況?如何解決這個問題?
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <iostream>
class DelayedAction
{
public:
DelayedAction():
work(service),
thread(boost::bind(&DelayedAction::run, this)),
timer(service)
{}
~DelayedAction()
{
thread.join();
}
void startAfter(const size_t delay)
{
timer.cancel();
timer.expires_from_now(boost::posix_time::seconds(delay));
timer.async_wait(boost::bind(&DelayedAction::action, this));
}
private:
void run()
{
service.run();
}
void action()
{
std::cout << "action" << std::endl;
}
boost::asio::io_service service;
boost::asio::io_service::work work;
boost::thread thread;
boost::asio::deadline_timer timer;
};
int main()
{
DelayedAction d;
for(int i = 1; i < 6; ++i)
{
Sleep(1000);
std::cout << i << " second(s)\n";
d.startAfter(10);
}
}
PS寫這個,我想真正的問題是boost :: deadline_timer一旦啓動就可以重啓。
謝謝,問題解決了!在我看來,這種行爲:取消行爲的結果是行爲的執行,是位計數器直觀的。 – Flaviu 2012-08-10 07:27:44
@FlaviuC如果解決了您的問題,請點擊綠色複選標記以接受答案。 – 2012-08-10 15:24:20