diff --git a/CppTimerCallback.h b/CppTimerCallback.h index 7f56fc3..233bf97 100644 --- a/CppTimerCallback.h +++ b/CppTimerCallback.h @@ -3,35 +3,31 @@ #include #include "CppTimer.h" #include +#include // Demo which creates a callback interface as the abstract class "Runnable". // This then allows to register a callback. class CppTimerCallback : public CppTimer { - + public: - class Runnable { - public: - virtual void run() = 0; - }; - - void registerEventRunnable(Runnable &h) { - cppTimerEventRunnable = &h; - } - - void unregisterEventRunnable() { - cppTimerEventRunnable = NULL; - } - - void timerEvent() { - if (cppTimerEventRunnable) { - cppTimerEventRunnable->run(); - } + class Runnable { + public: + virtual void run() = 0; + }; + + void registerEventRunnable(Runnable &h) { + cppTimerEventRunnables.push_back(&h); + } + + void timerEvent() { + for(auto & r : cppTimerEventRunnables) { + r->run(); } + } private: - Runnable* cppTimerEventRunnable = NULL; - + std::vector cppTimerEventRunnables; }; diff --git a/CppTimerStdFuncCallback.h b/CppTimerStdFuncCallback.h index 2a52781..c353c25 100644 --- a/CppTimerStdFuncCallback.h +++ b/CppTimerStdFuncCallback.h @@ -4,6 +4,7 @@ #include "CppTimer.h" #include #include +#include // This is a demo how to create a callback with std::function which allows // calling methods in other classes by registering a lambda function! @@ -15,17 +16,17 @@ class CppTimerCallback : public CppTimer { using CallbackFunction = std::function; void registerEventCallback(CallbackFunction cf) { - callbackFunction = cf; + callbackFunctions.push_back(cf); } void timerEvent() { - if (nullptr != callbackFunction) { - callbackFunction(); + for(auto &cb : callbackFunctions) { + cb(); } } private: - CallbackFunction callbackFunction = nullptr; + std::vector callbackFunctions; }; diff --git a/demo_runnable.cpp b/demo_runnable.cpp index 12e3e9f..1a4e1bb 100644 --- a/demo_runnable.cpp +++ b/demo_runnable.cpp @@ -32,10 +32,7 @@ int main( int, const char**) { // do nothing and keep sleeping for 2 secs std::this_thread::sleep_for(std::chrono::seconds(2)); - demoTimer1.unregisterEventRunnable(); demoTimer1.stop(); - - demoTimer2.unregisterEventRunnable(); demoTimer2.stop(); printf("\n");