Update Timer class to accept functions with any number of parameters
This commit is contained in:
+25
-1
@@ -1,6 +1,8 @@
|
||||
#ifndef UTIL_TIMER_H
|
||||
#define UTIL_TIMER_H
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <thread>
|
||||
@@ -15,13 +17,35 @@ public:
|
||||
Timer();
|
||||
~Timer();
|
||||
|
||||
void Start(int interval, std::function<void(void)> func);
|
||||
bool operator==(const Timer& other) const;
|
||||
|
||||
public:
|
||||
std::string Identifier() const;
|
||||
|
||||
template <typename ...FunctionArguments, typename ...Arguments>
|
||||
void Start(int interval, std::function<void(FunctionArguments...)> const & function, Arguments && ...arguments)
|
||||
{
|
||||
if (m_run.load(std::memory_order_acquire))
|
||||
Stop();
|
||||
|
||||
m_run.store(true, std::memory_order_release);
|
||||
m_thread = std::thread([this, interval, function, arguments ...]()
|
||||
{
|
||||
while (m_run.load(std::memory_order_acquire))
|
||||
{
|
||||
function(std::forward<Arguments>(arguments)...);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void Stop();
|
||||
bool IsRunning() const noexcept;
|
||||
void Wait();
|
||||
|
||||
private:
|
||||
std::atomic<bool> m_run;
|
||||
std::string m_identifier;
|
||||
std::thread m_thread;
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user