如何暂停和恢复提升截止日期计时器?

How to Pause & Resume Boost deadline timer?

本文关键字:日期 计时器 恢复 何暂停 暂停      更新时间:2023-10-16

是否可以使截止日期计时器停止并重新启动?

我正在c++库中开发一个播放器程序,需要一个能够暂停&简历,

我发现boost截止日期计时器是一个选项,但我如何在停止后重新启动它?

您的计时器应该异步等待。在这种情况下,您可以使用deadline_timer::cancel()取消计时器,使用deadline _timeer::expires_from_now()更改计时器到期时间,并使用deadlane_timer::async_wait()重新开始等待。

C++03的代码示例如下:

#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/chrono.hpp>
#include <boost/chrono/duration.hpp>
#include <boost/function.hpp>
#include <boost/thread.hpp>
/// Simple asio::deadline_timer wrapper to aggregate
/// timer, interval and handler function.
class timer
{
    typedef boost::asio::deadline_timer impl;
public:
    typedef impl::duration_type duration;
    typedef boost::function<void (boost::system::error_code, timer&)> handler_function;
    /// Create timer with specified interval and handler
    timer(boost::asio::io_service& io_service, duration interval, handler_function handler)
        : impl_(io_service)
        , interval_(interval)
        , handler_(handler)
    {
    }
    /// Start asynchronous waiting
    void start()
    {
        impl_.expires_from_now(interval_);
        impl_.async_wait(boost::bind(handler_, boost::asio::placeholders::error, boost::ref(*this)));
    }
    /// Stop waiting
    void stop()
    {
        impl_.cancel();
    }
private:
    impl impl_;
    duration interval_;
    handler_function handler_;
};
// Timer handler, just start next tick
void timer_tick(boost::system::error_code err, timer& t)
{
    static int tick_ = 0;
    if (!err)
    {
        std::cout << "tick " << ++tick_ << 'n';
        t.start();
    }
}
boost::asio::io_service io_service;
void timer_thread(timer& t)
{
    t.start();
    io_service.run();
}
int main()
{
    // run a timer in another thread
    timer t(io_service, boost::posix_time::seconds(1), timer_tick);
    boost::thread tthread(&timer_thread, boost::ref(t));
    // stop the timer after some delay
    boost::this_thread::sleep_for(boost::chrono::seconds(3));
    t.stop();
    tthread.join();
}

由于截止日期计时器使用io服务对象,您可以通过简单地停止服务来暂停计时器。