Skip to content

Commit

Permalink
now also with std::function
Browse files Browse the repository at this point in the history
  • Loading branch information
berndporr committed Feb 1, 2025
1 parent d2dc8f9 commit 4febd20
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 29 additions & 0 deletions CppTimerStdFuncCallback.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#ifndef __CPP_TIMER_CALLBACK
#define __CPP_TIMER_CALLBACK
#include <stdio.h>
#include "CppTimer.h"
#include <unistd.h>
#include <functional>

class CppTimerCallback : public CppTimer {

public:

using CallbackFunction = std::function<void(void)>;

void registerEventCallback(CallbackFunction cf) {
callbackFunction = cf;
}

void timerEvent() {
if (!(callbackFunction == nullptr)) {
callbackFunction();
}
}

private:
CallbackFunction callbackFunction;
};


#endif
43 changes: 43 additions & 0 deletions demo_stdfunccallback.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#include <stdio.h>
#include "CppTimerStdFuncCallback.h"
#include <unistd.h>
#include <thread>

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");

}

0 comments on commit 4febd20

Please sign in to comment.