2

最後の非同期イベントが発生してから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が開始された後に再起動できる方法だと思います。

4

1 に答える 1

2

呼び出すexpires_from_now()と、タイマーがリセットされ、ハンドラーがすぐに呼び出されてエラー コードが返されますboost::asio::error::operation_aborted

ハンドラーでエラー コードのケースを処理すると、期待どおりに動作させることができます。

void startAfter( const size_t delay)
{
    // no need to explicitly cancel
    // timer.cancel();
    timer.expires_from_now( boost::posix_time::seconds( delay));
    timer.async_wait( boost::bind( &DelayedAction::action, this, boost::asio::placeholders::error));
}

// ...

void action(const boost::system::error_code& e) 
{
    if(e != boost::asio::error::operation_aborted)
        std::cout << "action" << std::endl;
}

これについては、ドキュメントで説明されています: http://www.boost.org/doc/libs/1_47_0/doc/html/boost_asio/reference/deadline_timer.html

具体的には、次のタイトルのセクションを参照してください: アクティブなdeadline_timerの有効期限の変更

于 2012-08-09T16:44:58.787 に答える