如何暂停和恢复提升截止日期计时器?
How to Pause & Resume Boost deadline timer?
是否可以使截止日期计时器停止并重新启动?
我正在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服务对象,您可以通过简单地停止服务来暂停计时器。
相关文章:
- Linux的Cpp上的计时器
- 提升 ASIO 无法识别计时器对象
- 提升 asio 并发计时器取消问题与链
- 使用单体计时器的pthread_cond_timedwait有时会比预期晚超时
- 窗口中的微秒计时器
- 计时器是否从另一个线程启动?
- 如何在 c++ 中创建计时器
- C++回调计时器实现
- 在计时器或主线程外部的命令上销毁/替换线程
- 如何制作每秒从 30 乘 1 倒计时的计时器?
- 保留计时器集合(对象与指针)的最佳方法
- 在网络套接字计时器滴答后增加asio短读错误
- 是否可以仅使用标准 c++/c++11 实现不带"sleep"的计时器?
- 提升截止日期计时器的替代方案
- 如何在类定义中声明基本的截止日期计时器
- 截止日期计时器过期,现在怎么办
- io_service截止日期计时器不定期工作
- boost截止日期计时器在iOS中过期不准确
- 如何暂停和恢复提升截止日期计时器?
- boost截止日期计时器我的代码不能同时运行