最後の非同期イベントが発生してからn秒遅れた特定のアクションを1回実行したいと思います。したがって、連続するイベントがn秒未満で表示される場合、特定のアクションが遅延します(deadline_timerが再開されます)。
Boost deadline_timerの問題からタイマークラスを適応させました。簡単にするために、イベントは同期的に生成されます。コードを実行すると、次のようなものが期待されます。
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が開始された後に再起動できる方法だと思います。