gpt4 book ai didi

c++ - 使用 boost::deadline_timer 延迟 Action

转载 作者:搜寻专家 更新时间:2023-10-31 01:52:55 25 4
gpt4 key购买 nike

我想在最后一个异步事件发生后延迟 n 秒执行一次特定操作。因此,如果连续事件在不到 n 秒内出现,则特定操作将延迟(重新启动 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 启动后如何重新启动。

最佳答案

当您调用 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 的到期时间的部分

关于c++ - 使用 boost::deadline_timer 延迟 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11878091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com