Synopsis
namespace tpool { class timerpool { public: typedef implementation-defined timerid_t; implementation-defined s_stop_timer; implementation-defined s_current_timeout; timerpool(); explicit timerpool(boost::posix_time::time_duration const& prefire); ~timerpool(); template <typename Callback, typename Duration> timerid_t start_timer(Callback cb, Duration const& tout); bool stop_timer(timerid_t tid); }; }
Description
The timerpool constructor starts a thread. Then an application can start timers by using start_timer().
When a timer's timeout expires the timerpool thread executes the timer's callback.
The timerpool analyzes the return value of the callback. If the return value is timerpool::s_stop_timer the timer is stopped. If the return value is timerpool::s_current_timeout the timer is rearmed with the current timer's timeout. Otherwise, the timer's timeout is set to the return value and the timer is rearmed with the new timeout. If the return value is one of boost::date_time::special_values the result is undefined.
An instance of timepool does not catch exceptions thrown by callbacks. If a callback throws an exception terminate() will be called.
A callback can access the same or different instance of timepool and invoke start_timer() or stop_timer(). A callback can pass its own timerid to stop_timer().
timerpool holds no mutex locked while a timer's callback is running.
timerid_t is an unspecified integer type. An instance of timerid_t is a unique id of a timer. This id is unique among all timers of a timerpool. A timerpool never generates the same id twice. Different timerpools can generate equal ids.
An instance of timerpool is neither copyable nor assignable.
An instance of timerpool can be safely shared among threads.
Since timerpool is quite expensinve (due to the thread) it's usually best to have only one in an application.
timerpool()
timerpool(boost::posix_time::time_duration const& prefire)
~timerpool()
template <typename Callback, typename Duration> timerid_t start_timer(Callback cb, Duration const& timeout)
bool stop_timer(timerid_t tid)
Example
#include <timerpool/timerpool.hpp> #include <cstdlib> #include <iostream> #include <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using std::cout; using std::endl; namespace pt = boost::posix_time; pt::time_duration periodic() { cout << "periodic timer fired" << endl; return tpool::timerpool::s_current_timeout; } pt::time_duration disposable() { cout << "disposable timer fired" << endl; return tpool::timerpool::s_stop_timer; } pt::time_duration random_timer() { cout << "random timer fired" << endl; return pt::millisec(std::rand() % 1000); } int main(int, char const* []) { tpool::timerpool t1; t1.start_timer(periodic, pt::millisec(1000)); t1.start_timer(disposable, pt::millisec(1000)); t1.start_timer(random_timer, pt::millisec(1000)); boost::this_thread::sleep(pt::millisec(4950)); cout << endl; }