C++11 Timer wrappers based on Boost.Asio timers
- Repeatable
// set by construct argument or as below
timer.Recursive(true);
- Cancellable
// Stopped by destruction or as below
timer.Stop();
- Point-based or Duration-based
- Thread-safed callback supported by asio::strand as io executor
boost::asio::io_context ioc;
boost::asio::io_context::strand strand{ioc};
DurationTimer timer{strand, std::chrono::second{1}};
-
One-time timer by default
-
Declaration
template <class IntervalType = std::chrono::hours,
class IOExecutor = boost::asio::io_context,
class Timer = boost::asio::system_timer,
class TimePoint = GetTimeType<Timer>>
class PointTimer
- Example
auto second_from_now =
std::chrono::system_clock::now() + std::chrono::seconds{1};
boost::asio::io_context ioc;
PointTimer timer{ioc, second_from_now};
timer.Start([]() { std::cout << "timer expired." << std::endl; });
ioc.run();
-
Repeat by default
-
Declaration
template <class IntervalType = std::chrono::milliseconds,
class IOExecutor = boost::asio::io_context,
class Timer = boost::asio::steady_timer>
class DurationTimer
- Example
auto start_time = std::chrono::steady_clock::now();
boost::asio::io_context ioc;
DurationTimer timer{ioc, std::chrono::duration<double>{1}, false};
timer.Start([]() { std::cout << "timer expired." << std::endl; });
ioc.run();
- Example
using namespace boost::posix_time;
auto second_from_now = second_clock::universal_time() + seconds{1};
boost::asio::io_context ioc;
PointTimer<hours, boost::asio::io_context, boost::asio::deadline_timer> timer{
ioc, second_from_now};
timer.Start([]() { std::cout << "timer expired." << std::endl; });
ioc.run();
- Example
auto start_time = std::chrono::steady_clock::now();
boost::asio::io_context ioc;
boost::asio::io_context::strand strand{ioc};
DurationTimer timer{strand, std::chrono::second{1}, false};
timer.Start([]() { std::cout << "timer expired." << std::endl; });
ioc.run();