C++ Boost ASIO 简单的周期性定时器?
我想要一个非常简单的周期性计时器每 50 毫秒调用我的代码。我可以创建一个始终休眠 50 毫秒的线程(但这很痛苦)...我可以开始研究 Linux API 来制作计时器(但它不可移植)...
我喜欢 使用升压..我只是不确定这是否可能。 boost提供这个功能吗?
I want a very simple periodic timer to call my code every 50ms. I could make a thread that sleeps for 50ms all the time (but that's a pain)... I could start looking into Linux API's for making timers (but it's not portable)...
I'd like to use boost.. I'm just not sure it's possible. Does boost provide this functionality?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一个非常简单但功能齐全的示例:
请注意,调用
expires_at()
来设置新的到期时间非常重要,否则计时器将立即触发,因为当前的到期时间已经到期。A very simple, but fully functional example:
Notice that it is very important to call
expires_at()
to set a new expiration time, otherwise the timer will fire immediately because it's current due time already expired.Boosts Asio 教程的第二个示例对此进行了解释。
您可以在此处找到它。
之后,检查第三个示例 看看如何以周期性时间间隔再次调用它
The second example on Boosts Asio tutorials explains it.
You can find it here.
After that, check the 3rd example to see how you can call it again with a periodic time intervall
进一步扩展这个简单的例子。正如评论中所述,它将阻止执行,因此如果您希望运行更多 io_services,您应该像这样在线程中运行它们......
To further expand on this simple example. It will block the execution as was said in the comments, so if you want more io_services running, you should run them in a thread like so...
由于我对之前的答案有一些疑问,这是我的例子:
它做了它应该做的事情:数到五。愿它能帮助某人。
As I had some issues with prior answers, here is my example:
it did what it supposed to do: counting to five. May it help someone.
封装此功能的 Boost Asio 附加类(每 N 毫秒调用一个指定函数): https://github.com/mikehaben69/boost/tree/main/asio
该存储库包含演示源文件和 makefile。
A Boost Asio add-on class that encapsulates this functionality (call a specfied function every N milliseconds): https://github.com/mikehaben69/boost/tree/main/asio
The repo includes a demo source file and makefile.