延迟操作使用 boost::d eadline_timer
Delayed action using boost::deadline_timer
我想在最后一个异步事件发生后延迟 n 秒的特定操作执行一次。因此,如果连续事件在不到 n 秒内出现,则特定操作将延迟(deadline_timer重新启动)。
我从提升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::d eadline_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的到期时间的部分
相关文章:
- 是否需要在 Timer.5 boost::asio 教程中运行新线程?
- libevent是否允许在不同的线程中运行timer/io的回调
- QGraphicsView / Qgraphicsscene Timer事件不起作用
- 使用boost::asio::deadline_Timer实现通用Timer类时出现问题
- 创建 Timer 类时,我应该使用什么数据类型来保存值?(C/C++)
- C++ `Timer` class implementation
- 用c++编写Timer类
- Qt QLCDNumber Timer
- 在 c# 中是否有等效的 boost::timer::cpu_timer
- NachOS timer.cc 构造函数
- 在 c++ 中是否有像 timer 和 timertask 这样的东西,就像 java 一样
- c++计时器,相当于.NET System.Threading.timer
- 开始使用boost-cpu_timer时,错误:“boost::timer::cpu_timer”尚未声明
- 如何从boost::timer::cpu_timer获取以秒为单位的运行时间
- 如何为一些类(如timer类)编写单元测试
- 如何在c++中创建Timer任务
- Boost Timer 24小时格式
- 如何重启boost::timer::cpu_timer
- 在Timer ISR内使用FreeRTOS中的全局值
- Linux c++ timer周期性回调