当我尝试获取(未设置!)当前使用boost expires_from_now()的到期时间似乎实际上取消了计时器,但它实际上按预期运行,但最终没有调用处理程序.
换句话说,当使用expires_from_now()访问deadline_timer时,它会立即调用处理程序,而不会在处理程序到期时调用它.
请考虑以下代码和相应的输出:
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <iostream>
using namespace boost::posix_time;
using namespace std;
void handler1(const boost::system::error_code &ec)
{
if (ec == boost::asio::error::operation_aborted)
{
std::cout << microsec_clock::local_time() << " Handler1: Timer 1 was cancelled or retriggered." << std::endl;
}
else
{
std::cout << microsec_clock::local_time() << " Handler1: expired." << std::endl;
}
}
boost::asio::io_service io_service1;
class Mytimer {
public:
Mytimer();
void startTimer();
void runTimerThread();
bool isRunning();
private:
bool m_isRunning;
boost::asio::deadline_timer* m_pTimer;
boost::thread* m_pThread;
};
Mytimer::Mytimer() …Run Code Online (Sandbox Code Playgroud) 当您调用expires_from_now()正在运行的计时器时,将取消计时器,并调用新的计时器.因此调用关联的处理程序.在取消和已过期的计时器之间的处理程序中很容易区分.然而,我想知道,如果有一种方法来区分过期和重新触发的计时器.在这两个实例中,使用error_code调用处理程序operation_aborted.或许我错过了一些细节.
下面的代码生成以下输出:
20120415 21:32:28079507 Main: Timer1 set to 15 s.
20120415 21:32:28079798 Main: Timer1 set to 12 s.
20120415 21:32:28079916 Handler1: Timer 1 was cancelled or retriggered.
20120415 21:32:40079860 Handler1: expired.
Run Code Online (Sandbox Code Playgroud)
这表明处理程序无法为已取消的处理程序实现操作,因为重新触发计时器将调用相同的处理程序,从而执行相同的操作.这可能不是预期的行为.
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <iostream>
using namespace boost::posix_time;
using namespace std;
void handler1(const boost::system::error_code &ec)
{
if (ec == boost::asio::error::operation_aborted)
{
cout << microsec_clock::local_time() << " Handler1: Timer was cancelled or retriggered." << endl;
}
else
{
cout << …Run Code Online (Sandbox Code Playgroud)