是否可以使截止时间计时器停止并重新启动?
我正在开发一个c ++库中的播放器程序,需要一个能够暂停的计时器。履历,
我发现提升截止时间计时器是一个选项,但如何在停止后重启它?
答案 0 :(得分:3)
您的计时器应该异步等待。在这种情况下,您可以使用deadline_timer::cancel()取消计时器,使用deadline_timer :: expires_from_now()更改计时器到期时间,然后使用deadline_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();
}
答案 1 :(得分:0)
由于截止日期计时器使用an io service object,您可以通过stopping服务暂停计时器。