如何使用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