项目作者: andre237

项目描述 :
C++ timer implementation to rhythmically execute a given task
高级语言: C++
项目地址: git://github.com/andre237/timed-task.git
创建时间: 2019-09-27T19:53:20Z
项目社区:https://github.com/andre237/timed-task

开源协议:

下载


timed-task

C++ timer implementation to rhythmically execute a given task

Easy to use, header only, timer. Just inherit the TimerTask class into your own class and define what the timer should do. Here’s an example:

  1. #include <iostream>
  2. #include "timed-task.h"
  3. class UpdateTask : public TimerTask {
  4. public:
  5. explicit UpdateTask(uint64_t rate, TimeUnit ratio) :
  6. TimerTask(rate, ratio) {}
  7. private:
  8. void doAction() override {
  9. std::cout << "update task\n";
  10. }
  11. };
  12. int main() {
  13. // once instantiated, it is running (RAII-style)
  14. UpdateTask update(100, TimeUnit::milliseconds);
  15. std::this_thread::sleep_for(std::chrono::seconds(60));
  16. // going out of scope immediately stops it
  17. // no need to worry on stopping it manually
  18. return 0;
  19. }

The timer performs cadencing/compensation at every single execution to ensure the rhythm is kept all along. Don’t worry if your doAction() implementation may take a while. The timer is here to balance it. See example above:

  1. void doAction() override {
  2. std::random_device rd;
  3. std::mt19937 eng(rd()); //
  4. std::uniform_int_distribution<> distr(1, 5);
  5. int t = distr(eng) * 10;
  6. std::this_thread::sleep_for(std::chrono::milliseconds(t));
  7. std::cout << "update task " << t << std::endl;
  8. // even tough this method's execution time is random
  9. // the timer will keep the execution cadenced
  10. }

Built-in statistics are available as well, enabled by default:

  1. Samples taken: 800
  2. Deviation average: 0.077079 milliseconds
  3. Compensation average: 69.131133 milliseconds
  4. Max variance: 0.134759 milliseconds
  5. Min variance: 0.006714 milliseconds
  6. Tolerance exceeded 0 times