linux版本中间件

TimeScheduler.cpp 969B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include "TimeScheduler.h"
  2. #include <thread>
  3. #include <functional>
  4. #include "Log.h"
  5. TimeScheduler::TimeScheduler():timer_(io_)
  6. {
  7. }
  8. TimeScheduler::~TimeScheduler()
  9. {
  10. m_ITimes.clear();
  11. io_.stop();
  12. }
  13. void TimeScheduler::startTimer()
  14. {
  15. std::thread([&] {
  16. timer_.expires_from_now(boost::asio::chrono::seconds(1));
  17. timer_.async_wait(std::bind(&TimeScheduler::__onTimer, this, std::placeholders::_1));
  18. io_.run();
  19. }).detach();
  20. }
  21. void TimeScheduler::attachITimer(ITimer *pTimer)
  22. {
  23. m_ITimes.emplace_back(pTimer);
  24. }
  25. void TimeScheduler::detachITimer(ITimer *pTimer)
  26. {
  27. m_ITimes.remove(pTimer);
  28. }
  29. void TimeScheduler::__onTimer(const error_code& ec)
  30. {
  31. /*static int i = 0;
  32. i++;
  33. std::cout << i << std::endl;*/
  34. for (ITimer* val:m_ITimes)
  35. {
  36. if (val)
  37. val->onTimer();
  38. }
  39. timer_.expires_from_now(boost::asio::chrono::seconds(1));
  40. timer_.async_wait(std::bind(&TimeScheduler::__onTimer, this, std::placeholders::_1));
  41. }
  42. TimeScheduler TimeScheduler::instance;