24 #include <condition_variable>
32 template<
class Signature,
class Function = std::function<Signature>>
34 typedef std::chrono::system_clock TimerClock;
37 timerName_(timerName), isThreadRun_(false), isTimerRun_(false), callback_([]{})
46 if (isThreadRun_ && timerThread_.joinable()) {
47 std::unique_lock<std::mutex> timerLock(timerGuard_);
50 condition_.notify_one();
58 void start(std::size_t seconds,
const Function& callback)
65 KAA_LOG_TRACE(boost::format(
"Timer[%1%] scheduling for %2% sec ...") % timerName_ % seconds );
68 std::unique_lock<std::mutex> timerLock(timerGuard_);
73 timerThread_ = std::thread([&] { run(); });
77 endTS_ = TimerClock::now() + std::chrono::seconds(seconds);
80 condition_.notify_one();
86 KAA_LOG_TRACE(boost::format(
"Timer[%1%] stopping ...") % timerName_);
89 std::unique_lock<std::mutex> timerLock(timerGuard_);
94 condition_.notify_one();
101 KAA_LOG_TRACE(boost::format(
"Timer[%1%] starting thread ...") % timerName_);
104 std::unique_lock<std::mutex> timerLock(timerGuard_);
107 while (isThreadRun_) {
109 auto now = TimerClock::now();
111 KAA_LOG_TRACE(boost::format(
"Timer[%1%] executing callback ...") % timerName_);
114 auto currentCallback = callback_;
127 condition_.wait_for(timerLock, (endTS_ - now));
132 condition_.wait(timerLock);
139 const std::string timerName_;
144 std::thread timerThread_;
145 std::condition_variable condition_;
147 std::mutex timerGuard_;
149 std::chrono::time_point<TimerClock> endTS_;
KaaTimer(const std::string &timerName)
#define KAA_MUTEX_UNLOCKING(mutex_name)
#define KAA_MUTEX_LOCKED(mutex_name)
#define KAA_LOG_TRACE(message)
void start(std::size_t seconds, const Function &callback)
#define KAA_LOG_WARN(message)
#define KAA_MUTEX_UNLOCKED(mutex_name)
#define KAA_MUTEX_LOCKING(mutex_name)