Skip to content

Instantly share code, notes, and snippets.

@bo0ts
Created November 18, 2012 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bo0ts/4108222 to your computer and use it in GitHub Desktop.
Save bo0ts/4108222 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/asio/deadline_timer.hpp>
class TimerThing
{
protected:
boost::asio::deadline_timer* statusTimer_;
boost::thread_group worker_threads_;
boost::asio::io_service io_service_;
boost::shared_ptr<boost::asio::io_service::work> work_;
public:
TimerThing() {}
virtual ~TimerThing(){}
void updateStatus(const boost::system::error_code& ec)
{
if (ec == boost::asio::error::operation_aborted)
return;
std::cout<<"Status Update"<<std::endl;
statusTimer_->expires_at(statusTimer_->expires_at() + boost::posix_time::seconds(1));
statusTimer_->async_wait(boost::bind(&TimerThing::updateStatus, this, boost::asio::placeholders::error));
}
void start()
{
statusTimer_=new boost::asio::deadline_timer(io_service_);
boost::shared_ptr<boost::asio::io_service::work> myWork(new boost::asio::io_service::work(io_service_));
work_=myWork;
worker_threads_.create_thread( boost::bind( &TimerThing::threadAction, this ) );
statusTimer_->expires_at(statusTimer_->expires_at() + boost::posix_time::seconds(1));
statusTimer_->async_wait(boost::bind(&TimerThing::updateStatus, this, boost::asio::placeholders::error));
}
void threadAction()
{
io_service_.run();
}
void stop()
{
work_.reset();
io_service_.stop();
worker_threads_.join_all();
delete statusTimer_;
}
};
int main()
{
TimerThing t;
std::string input;
std::cout<<"Press f to stop"<<std::endl;
t.start();
std::cin>>input;
t.stop();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment