Advertisement
obernardovieira

My Timer Library (v1.0)

Feb 24th, 2014
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. //My Timer Library
  2.  
  3. #include <iostream>
  4. #include <map>
  5. #include <tuple>
  6. #include <functional>
  7. #include <thread>
  8. #include <chrono>
  9.  
  10. struct timer_config {
  11.     bool activ_e;
  12.     int millisecond_s;
  13.     bool repea_t;
  14.     std::function<void()> fun_c;
  15. };
  16. std::map<int, timer_config> timer_reg;
  17. int total_timers = 0;
  18. void run_timer(int timerid) {
  19.     std::thread( [](int idtimer) {
  20.         std::map<int, timer_config>::const_iterator k = timer_reg.find(idtimer);
  21.         if(k != timer_reg.end()) {
  22.             timer_config Timer = k->second;
  23.             std::this_thread::sleep_for(std::chrono::milliseconds(Timer.millisecond_s));
  24.             k = timer_reg.find(idtimer);
  25.             if(k != timer_reg.end()) {
  26.                 Timer = k->second;
  27.                 if(Timer.activ_e == true) {
  28.                     Timer.fun_c();
  29.                     if(Timer.repea_t == true) {
  30.                         run_timer(idtimer);
  31.                     }
  32.                 }
  33.             }
  34.         }
  35.     },timerid).detach();
  36. }
  37. int start_timer(std::function<void()> funcao, int milliseconds, bool repeat) {
  38.     timer_config Config;
  39.     total_timers++;
  40.     Config.fun_c = funcao;
  41.     Config.millisecond_s = milliseconds;
  42.     Config.activ_e = true;
  43.     Config.repea_t = repeat;
  44.     timer_reg.insert(std::make_pair(total_timers, Config));
  45.     run_timer(total_timers);
  46.     return total_timers;
  47. }
  48. void kill_timer(int timerid) {
  49.     std::map<int, timer_config>::iterator k = timer_reg.find(timerid);
  50.     if(k != timer_reg.end()) {
  51.         timer_config Timer = k->second;
  52.         Timer.activ_e = false;
  53.         k->second = Timer;
  54.     }
  55. }
  56.  
  57.  
  58. //example usage
  59.  
  60. void cars(int n) {
  61.     std::cout << n << std::endl;
  62. }
  63.  
  64. int main() {
  65.  
  66.     int mytimer = start_timer(std::bind(cars, 7),2000,true);
  67.     //kill_timer(mytimer);
  68.  
  69.  
  70.     return 1;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement