使用Boost DateTime在C 中进行超时

Timeout in C++ using Boost datetime

本文关键字:超时 Boost DateTime 使用      更新时间:2023-10-16

如何使用boost :: datetime在C 中循环时如何实现超时?

类似:

#define TIMEOUT 12
while(some_boost_datetime_expression(TIMEOUT))
{
    do_something(); // do it until timeout expires
}
// timeout expired

使用boost :: deadline_timer进行超时。循环中值的不断检查对于CPU而言是过度的。

您首先要标记您开始的时间,然后计算当前时间和启动时间之间的差异。没有内置的Boost DateTime表达式将完全像您描述的那样工作。在Boost DateTime术语中:http://www.boost.org/doc/libs/1_51_0/doc/doc/html/date_time.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 DateTime代码,而只是在Boost网站上阅读文档和示例代码。)

您只需检查时间差:

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
}

但是,您可以重新考虑您的设计。

这可以通过boost.asio轻松完成。启动deadline_timer作为一个异步过程。它在过期时取消事件循环。继续将您的工作发布到同一事件循环直到运行。工作解决方案:

#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;
}