我的应用程序是一个多线程应用程序,我创建一个线程,该线程不断读取套接字上的数据以连续检查来自服务器的通知,而其他线程在每次 t(例如 20 秒)后向服务器发送请求。 我正在使用 boost 来做同样的事情。 我读到了有关 boost::asio 的内容,并发现了一个计时器函数deadline_timer()。但根据我的理解,它仅异步触发一次,但我的要求是每次计时器 t 到期时连续调用发送。 我该如何实施呢? 预先感谢。
您可以简单地从计时器的处理程序中再次触发计时器:
#include <iostream>
#include <boost/asio.hpp>
using namespace std;
int stop_after = 3;
void async_wait_timer(boost::asio::deadline_timer& t, int seconds)
{
t.expires_from_now(boost::posix_time::seconds{1});
t.async_wait(
[&] (const boost::system::error_code& e)
{
--stop_after;
if(!e || !stop_after)
{
async_wait_timer(t, seconds);
}
});
}
int main()
{
boost::asio::io_service svc;
boost::asio::deadline_timer timer{svc};
async_wait_timer(timer, 1);
svc.run();
return 0;
}
通过在其中放置一个带有deadline_timer的连续循环来解决需求,直到我的系统关闭。
while(!shutdown==true)
{
boost::asio::io_service io;
boost::asio::deadline_timer timer(io, boost::posix_time::seconds(10)); timer.async_wait(&check_faults);
io.run();
}
如果有人可以提供更好的方法,请发表您的评论,我将非常感激。
这是一个例子:
适用于 C++20 应用程序的跨平台灵活定时器调度程序(仅标头类):https://github.com/AmitGDev/Scheduler/blob/master/Scheduler/Scheduler.h
像这样使用它:
void main()
{
class Model final
{
public:
void Test()
{
std::cout << "* test re-activate the timer 5 times" << std::endl;
scheduler_.ScheduleTimer(1, 1000, &Model::OnTimer, this, 5); // <--
// Sleep for a while to let the timer expire
std::this_thread::sleep_for(std::chrono::seconds(6));
}
protected:
Scheduler scheduler_{};
void OnTimer(uint64_t timer_id, uint8_t n) // n - Extra parameter
{
if (n > 0) {
std::osyncstream sync_stream(std::cout);
sync_stream << "timer " << timer_id << " expired" << std::endl;
scheduler_.ScheduleTimer(timer_id, 1000, &Model::OnTimer, this, n - 1); // <--
}
}
};
Model model{};
model. Test();
}