如何使用boost :: datetime在C++中實現超時while循環?C++中使用Boost超時時間datetime
類似:
#define TIMEOUT 12
while(some_boost_datetime_expression(TIMEOUT))
{
do_something(); // do it until timeout expires
}
// timeout expired
如何使用boost :: datetime在C++中實現超時while循環?C++中使用Boost超時時間datetime
類似:
#define TIMEOUT 12
while(some_boost_datetime_expression(TIMEOUT))
{
do_something(); // do it until timeout expires
}
// timeout expired
使用Boost::deadline_timer的超時。對循環中的值進行常量檢查對於CPU來說是矯枉過正的。
實際上並非如此:一個空的while()循環會過度殺傷,在這種情況下,我們得到了一個在非零時間執行的do_something()函數。 –
+1使用asio –
首先您要標記您開始的時間,然後計算出當前時間和您開始的時間之間的差異。沒有內置的增強日期時間表達式可以完全像你描述的那樣工作。在助推日期時間術語:http://www.boost.org/doc/libs/1_51_0/doc/html/date_time.html您的超時時間是「持續時間」,您開始的點是「時間點」。
假設你想內第二是準確的,並有4分鐘2秒的時間間隔。
using namespace boost::posix_time;
ptime start = second_clock::local_time();
給你一個時間點開始你的時間
ptime end = start + minutes(4)+seconds(2);
讓你從現在4分鐘2秒的時間點。
然後
(second_clock::local_time() < end)
爲真當且僅當當前時間的結束時間之前。
(免責聲明:這不是基於關閉之前實際寫入任何提振日期時間的代碼,而只是閱讀的文檔和示例代碼了在升壓站。)
你可以只檢查的時間差:
boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
while((boost::posix_time::microsec_clock::local_time() - now) < boost::posix_time::milliseconds(TIMEOUT))
{
// do something
}
但是不要做那樣的事情,你可能會重新考慮你的設計。
這很簡單,正是我所需要的。我需要對某件事進行檢查,但只想在最長時間內做到這一點,在此之後,如果它(我正在檢查的)不處於我希望的狀態,那麼繼續,不管後果如何。 – Jon
這可以很容易地與boost.Asio完成。作爲一個異步進程啓動deadline_timer。它在事件循環到期時取消。繼續將您的工作發佈到相同的事件循環,直到它正在運行。 A工作液:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
class timed_job
{
public:
timed_job(int timeout) :
timer_(io_service_, boost::posix_time::seconds(timeout)) // Deadline timer
{
}
void start()
{
// Start timer
timer_.async_wait
(
boost::bind
(
&timed_job::stop, this
)
);
// Post your work
io_service_.post
(
boost::bind
(
&timed_job::do_work, this
)
);
io_service_.run();
std::cout << "stopped." << std::endl;
}
private:
void stop()
{
std::cout << "call stop..." << std::endl;
io_service_.stop();
}
void do_work()
{
std::cout << "running..." << std::endl;
// Keep posting the work.
io_service_.post
(
boost::bind
(
&timed_job::do_work, this
)
);
}
private:
boost::asio::io_service io_service_;
boost::asio::deadline_timer timer_;
};
int main()
{
timed_job job(5);
job.start();
return 0;
}
您可以使用其他的方法。 – logoff
你是對的,但讓我們假裝我想做按照問題... –
是'do_something',要超時後取消長時間運行的作業,或者是你想要做一個簡短的工作反覆超時? – Vikas