fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <map>
  4. #include <string>
  5. using namespace std;
  6.  
  7. // IntervalManager
  8. class TaskManager {
  9. private:
  10. int time = 0;
  11. // Event Struct
  12. class MyEvent {
  13. public:
  14. int timeout;
  15. int interval;
  16. function<void()> func;
  17. };
  18. map<string, MyEvent> taskMap;
  19.  
  20. public:
  21. void setInterval(string name, int interval, function<void()> func){
  22. MyEvent ev;
  23. ev.timeout = interval + this->time;
  24. ev.interval = interval;
  25. ev.func = func;
  26. this->taskMap[name] = ev;
  27. }
  28. void setTimeout(string name, int timeout, function<void()> func){
  29. MyEvent ev;
  30. ev.timeout = timeout + this->time;
  31. ev.interval = -1; //mark
  32. ev.func = func;
  33. this->taskMap[name] = ev;
  34. }
  35.  
  36. void execute(){
  37.  
  38. for(auto ite = this->taskMap.begin();
  39. ite != this->taskMap.end();){
  40. auto &name = ite->first;
  41. auto &ev = ite->second;
  42.  
  43. if(ev.timeout == this->time){
  44. // Execute!
  45. ev.func();
  46.  
  47. if( ev.interval != -1){
  48. // than interval
  49. // reset timeout;
  50. ev.timeout = ev.interval + this->time;
  51. }
  52. else{
  53. // than timeout
  54. // erase
  55. this->taskMap.erase(ite++);
  56. continue;
  57. }
  58. }
  59. ite++;
  60. }
  61. //Time count up
  62. this->time++;
  63. } // end of execute()
  64.  
  65. void clearInterval(string name){
  66. auto ite = this->taskMap.find(name);
  67. this->taskMap.erase(ite);
  68. }
  69. };
  70.  
  71. int main() {
  72. // your code goes here
  73.  
  74. // create interval manager
  75. TaskManager tasks;
  76.  
  77. // setTimeout
  78. tasks.setTimeout("helloTask", 3,
  79. [&](){cout << "timeout" << endl;}
  80. );
  81.  
  82. // setInterval
  83. tasks.setInterval("interval", 2,
  84. [&](){cout<<"interval"<<endl;}
  85. );
  86.  
  87. for(int i = 0; i < 10; i++){
  88. cout<<"▼ : "+to_string(i)+" loop"<<endl;
  89. tasks.execute();
  90. cout<<"▲"<<endl;
  91. }
  92.  
  93. return 0;
  94. }
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
▼ : 0 loop
▲
▼ : 1 loop
▲
▼ : 2 loop
interval
▲
▼ : 3 loop
timeout
▲
▼ : 4 loop
interval
▲
▼ : 5 loop
▲
▼ : 6 loop
interval
▲
▼ : 7 loop
▲
▼ : 8 loop
interval
▲
▼ : 9 loop
▲