支持任意形式的函数
class SimpleTimer
{
public:
SimpleTimer()
{
}
~SimpleTimer()
{
m_bStop = true;
if (m_pThread)
{
m_pThread->join();
delete m_pThread;
}
}
unsigned int Interval() const
{
return m_uiMsecInterval;
}
void Interval(unsigned int uiMsecInterval)
{
m_uiMsecInterval = uiMsecInterval;
}
template<typename F, typename... Arg>
bool Start(F&& func, Arg&&... arg)
{
if (m_uiMsecInterval <= 0)
return false;
if (m_pThread)
{
m_bStop = true;
m_pThread->join();
delete m_pThread;
}
m_bStop = false;
m_pThread = new std::thread([&, this] {
auto task = std::bind(std::forward<F>(func), std::forward<Arg>(arg)...);
while (!m_bStop)
{
task();
std::this_thread::sleep_for(std::chrono::milliseconds(m_uiMsecInterval));
}
});
return true;
}
void Stop()
{
m_bStop = true;
}
SimpleTimer(const SimpleTimer&) = delete;
SimpleTimer(SimpleTimer&&) = delete;
SimpleTimer& operator =(const SimpleTimer&) = delete;
SimpleTimer& operator =(SimpleTimer&&) = delete;
private:
unsigned int m_uiMsecInterval = -1;
std::thread* m_pThread = nullptr;
bool m_bStop = false;
};
|