102 lines
1.8 KiB
C++
102 lines
1.8 KiB
C++
/**
|
|
* @file include/di/Timer.h
|
|
* @brief Generic timer class
|
|
* @date June 2, 2015
|
|
* @author J.J.J. Jacobs, R.W.A. van der Heijden
|
|
* @copyright 2015 Dual Inventive Technology Centre B.V.
|
|
*
|
|
* General purpose timer class including callback mechanism
|
|
*/
|
|
#ifndef INCLUDE_DI_TIMER_H_
|
|
#define INCLUDE_DI_TIMER_H_
|
|
|
|
#include <memory>
|
|
#include <thread>
|
|
#include <chrono>
|
|
#include <functional>
|
|
#include <atomic>
|
|
#include <mutex>
|
|
|
|
namespace Di {
|
|
/**
|
|
* @class Timer
|
|
*
|
|
* Generic timer class
|
|
*/
|
|
class Timer {
|
|
public:
|
|
/**
|
|
* Constructor
|
|
*/
|
|
Timer();
|
|
|
|
/**
|
|
* Destructor
|
|
*/
|
|
~Timer();
|
|
|
|
/**
|
|
* Set duration of timer
|
|
* - Save timer duration
|
|
* - Calculate end time with now() + d
|
|
* @param d Duration
|
|
*/
|
|
void set(std::chrono::milliseconds d);
|
|
|
|
/**
|
|
* Reset timer
|
|
* - Calculate new end time with now() previous set duration
|
|
*/
|
|
void reset(void);
|
|
|
|
/**
|
|
* Set timer in "running" state
|
|
*/
|
|
void start(void);
|
|
|
|
/**
|
|
* Set timer in "non-running" state
|
|
*/
|
|
void stop(void);
|
|
|
|
/**
|
|
* Set callback for timeout
|
|
* @note This function may only be called before the timer is started or when the timer is stopped
|
|
* @param func Callback function
|
|
*/
|
|
void setCallback(std::function<void(Timer *)> func);
|
|
|
|
/**
|
|
* Check if timer has elapsed
|
|
* @return false When timer is non-running or not expired
|
|
* @return true When timer has elapsed
|
|
*/
|
|
bool isElapsed(void);
|
|
|
|
/**
|
|
* function to immediately trigger the timeout
|
|
*/
|
|
void trigger(void);
|
|
|
|
private:
|
|
std::atomic_bool __stopped;
|
|
|
|
std::mutex __endLock; ///< mutex to lock the __duration and __end access
|
|
std::chrono::milliseconds __duration;
|
|
std::chrono::steady_clock::time_point __end;
|
|
|
|
std::function<void(Timer *)> __callback;
|
|
std::shared_ptr<std::thread> __t;
|
|
std::atomic_bool __hasReset;
|
|
|
|
/**
|
|
* Callback thread
|
|
*/
|
|
void __callCallback(void);
|
|
};
|
|
|
|
} // namespace Di
|
|
|
|
|
|
#endif // INCLUDE_DI_TIMER_H_
|