I am trying to perform a task on an interval and I made a POC using boost::asio::steady_timer.
It ends up there is nothing wrong with the timer.
Try the following test:
- Run the program and do not touch the mouse
- Observe the console window output updating every second
Now try this test:
- Run the program again
- Let it run a bit and observe the output updating every second
- Set a breakpoint inside the timer callback
- Left click on the console window
- Observe that the timer callback no longer gets hit
- Right click on the console window
- Observe the program continues executing as normal
Can someone explain this behavior? Does std::cout block when you left click on the console window until you right click on it?
#include <boost/asio.hpp>
#include "boost/asio/deadline_timer.hpp"
#include<boost/bind.hpp>
#include <chrono>
#include <iostream>
class Pooper
{
boost::asio::io_context & m_ioContext;
boost::asio::steady_timer m_timer;
public:
Pooper(boost::asio::io_context & ioContext)
:
m_ioContext(ioContext)
, m_timer(boost::asio::steady_timer(ioContext))
{
}
void Run()
{
m_timer.expires_from_now(std::chrono::seconds(1));
m_timer.async_wait(boost::bind(&Pooper::OnTimerExpired, this, boost::asio::placeholders::error));
}
void OnTimerExpired(const boost::system::error_code & error)
{
if (error.failed())
{
std::cerr << "boost error: Failed" << std::endl;
}
std::cout << "Poop" << std::endl;
try
{
// Do stuff here later
m_timer.expires_from_now(std::chrono::seconds(1));
m_timer.async_wait(boost::bind(&Pooper::OnTimerExpired, this, boost::asio::placeholders::error));
}
catch (std::exception &)
{
std::cerr << "An exception occured." << std::endl;
}
}
};
int main()
{
boost::asio::io_context ioContext;
auto pooper = Pooper(ioContext);
pooper.Run();
ioContext.run();
std::cerr << "Exited..." << std::endl;
}
Using:
- boost 1.70.0 from nuget along with the vc-142 libs
- Visual Studio 2019