diff --git a/CMakeLists.txt b/CMakeLists.txt index de8c1c2..34ead91 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,6 +17,10 @@ TARGET_LINK_LIBRARIES(demo cpptimer) add_executable(demo_runnable demo_runnable.cpp) TARGET_LINK_LIBRARIES(demo_runnable cpptimer) +add_executable(demo_stdfunccallback demo_stdfunccallback.cpp) +TARGET_LINK_LIBRARIES(demo_stdfunccallback cpptimer) + + add_subdirectory(test) set_target_properties(cpptimer PROPERTIES diff --git a/CppTimerStdFuncCallback.h b/CppTimerStdFuncCallback.h new file mode 100644 index 0000000..2c02f8b --- /dev/null +++ b/CppTimerStdFuncCallback.h @@ -0,0 +1,29 @@ +#ifndef __CPP_TIMER_CALLBACK +#define __CPP_TIMER_CALLBACK +#include +#include "CppTimer.h" +#include +#include + +class CppTimerCallback : public CppTimer { + +public: + + using CallbackFunction = std::function; + + void registerEventCallback(CallbackFunction cf) { + callbackFunction = cf; + } + + void timerEvent() { + if (!(callbackFunction == nullptr)) { + callbackFunction(); + } + } + +private: + CallbackFunction callbackFunction; +}; + + +#endif diff --git a/demo_stdfunccallback.cpp b/demo_stdfunccallback.cpp new file mode 100644 index 0000000..5d30864 --- /dev/null +++ b/demo_stdfunccallback.cpp @@ -0,0 +1,43 @@ +#include +#include "CppTimerStdFuncCallback.h" +#include +#include + +class ReceiverClass1 { +public: + void run() { + fprintf(stdout,"Bah! "); + fflush(stdout); + } +}; + + +class ReceiverClass2 { +public: + void run() { + fprintf(stdout,"Buh! \n"); + fflush(stdout); + } +}; + + +int main( int, const char**) { + CppTimerCallback demoTimer1; + ReceiverClass1 receiverClass1; + demoTimer1.registerEventCallback([&receiverClass1](){receiverClass1.run();}); + demoTimer1.startns(77000000); + + CppTimerCallback demoTimer2; + ReceiverClass2 receiverClass2; + demoTimer2.registerEventCallback([&receiverClass2](){receiverClass2.run();}); + demoTimer2.startns(250000000); + + // do nothing and keep sleeping for 2 secs + std::this_thread::sleep_for(std::chrono::seconds(2)); + + demoTimer1.stop(); + demoTimer2.stop(); + + printf("\n"); + +}