Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //My Timer Library
- #include <iostream>
- #include <map>
- #include <tuple>
- #include <functional>
- #include <thread>
- #include <chrono>
- struct timer_config {
- bool activ_e;
- int millisecond_s;
- bool repea_t;
- std::function<void()> fun_c;
- };
- std::map<int, timer_config> timer_reg;
- int total_timers = 0;
- void run_timer(int timerid) {
- std::thread( [](int idtimer) {
- std::map<int, timer_config>::const_iterator k = timer_reg.find(idtimer);
- if(k != timer_reg.end()) {
- timer_config Timer = k->second;
- std::this_thread::sleep_for(std::chrono::milliseconds(Timer.millisecond_s));
- k = timer_reg.find(idtimer);
- if(k != timer_reg.end()) {
- Timer = k->second;
- if(Timer.activ_e == true) {
- Timer.fun_c();
- if(Timer.repea_t == true) {
- run_timer(idtimer);
- }
- }
- }
- }
- },timerid).detach();
- }
- int start_timer(std::function<void()> funcao, int milliseconds, bool repeat) {
- timer_config Config;
- total_timers++;
- Config.fun_c = funcao;
- Config.millisecond_s = milliseconds;
- Config.activ_e = true;
- Config.repea_t = repeat;
- timer_reg.insert(std::make_pair(total_timers, Config));
- run_timer(total_timers);
- return total_timers;
- }
- void kill_timer(int timerid) {
- std::map<int, timer_config>::iterator k = timer_reg.find(timerid);
- if(k != timer_reg.end()) {
- timer_config Timer = k->second;
- Timer.activ_e = false;
- k->second = Timer;
- }
- }
- //example usage
- void cars(int n) {
- std::cout << n << std::endl;
- }
- int main() {
- int mytimer = start_timer(std::bind(cars, 7),2000,true);
- //kill_timer(mytimer);
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement