当我尝试获取(未设置!)使用 boost expires_from_now() 的当前到期时间似乎实际上取消了计时器,但它实际上按预期运行,但最终没有调用处理程序。
或者换句话说,当使用 expires_from_now() 访问 deadtime_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()
: m_pTimer(NULL),
m_pThread(NULL)
{
m_pTimer = new boost::asio::deadline_timer(io_service1);
m_pTimer->async_wait(handler1);
}
void Mytimer::runTimerThread()
{
io_service1.run();
}
void Mytimer::startTimer()
{
m_pThread = new boost::thread(&Mytimer::runTimerThread, this);
m_pTimer->expires_from_now(boost::posix_time::seconds(10));
}
bool Mytimer::isRunning()
{
time_duration td = m_pTimer->expires_from_now();
if (td.total_seconds() > 0)
{
return true;
}
return false;
}
int main()
{
time_facet *facet = new time_facet("%Y%m%d %H:%M:%S%f");
std::cout.imbue(std::locale(std::cout.getloc(), facet));
cout << microsec_clock::local_time() << " before timer construction" << endl;
Mytimer timer;
cout << microsec_clock::local_time() << " before startTimer()" << endl;
timer.startTimer();
cout << microsec_clock::local_time() << " IsRunning: " << timer.isRunning() << endl;
for (int i = 0; i <= 20; i++)
{
sleep(1);
cout << microsec_clock::local_time() << " IsRunning: " << timer.isRunning() << endl;
}
}
20120412 22:41:45689235 在计时器构造之前
20120412 22:41:45689514 在 startTimer() 之前
20120412 22:41:45689619 IsRunning: 1
20120412 22:41:45689693 Handler1:计时器 1 已取消或重新触发。
20120412 22:41:46689792 ISRUNGNUSN:1
20120412 22:41:47689994 ISRUNNNUMNNIUNN:1
20120412 22:41:48690179 ISRUNNUNNINNE:1
20120412 22:41:
41:41:49690375
ISRINN 51690712 ISRUNNNING:1
20120412 22:41:52690884 ISRUNNNUMN:1
20120412 22:41:53691069 ISRINNUNN:1
20120412 22:41:41:
41:
41:54691236 ISRUNNINN
20120412 22:41:57691810 Isrunning:0
20120412 22:41:58692001 ISRUNNNING:0
20120412 22:41:59692193 ISRUNNINNE:0
20120412 22:42:
42:00692364 ISRINNUMNING
ISRINNUMN 02692706 IsRunning: 0
20120412 22:42:03692886 IsRunning: 0
20120412 22:42:04693071 IsRunning: 0
20120412 22:42:05693267 IsRunning: 0
20120412 22:42:066934