/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <iostream>
#include <vector>
#include <time.h>
using namespace std;
typedef void (*funcp_t)();
clock_t start = clock();
int millis() {
return clock() - start;
}
class Action {
public:
Action(int interval ,funcp_t callback ) : _interval(interval) , _callback(callback)
{
}
bool trigger(int now) {
if (now - _lastCheck > _interval) {
_lastCheck = now;
return true;
}
cout << "now: " << now;
cout << ", last: " << _lastCheck;
cout << ", interval: " << _interval;
cout << ", diff: " << (now - _lastCheck);
cout << endl;
return false;
}
void fire() {
cout << "action fired. last check: " << _lastCheck << endl;
_callback();
}
private:
int _interval = 0;
int _lastCheck = 0;
funcp_t _callback;
};
class ActionManager {
public:
void addAction(Action *action) {
_actions.push_back(action);
}
void tick() {
int now = millis();
for(auto action : _actions) {
if(action->trigger(now)) {
action->fire();
}
}
}
private:
vector<Action *> _actions;
};
void sayHi() {
cout << "oh hi" << endl;
}
void sayHey() {
cout << "hey there" << endl;
}
ActionManager manager = ActionManager();
Action hiAction = Action(500000, sayHi);
Action heyAction = Action(100000, sayHey);
int main()
{
cout<<"--> Start <--" << endl;
manager.addAction(&hiAction);
manager.addAction(&heyAction);
while(true){
manager.tick();
cout << endl;
}
return 0;
}