中间件底层,websocket

Scheduler.cpp 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include "stdafx.h"
  2. #include "Scheduler.h"
  3. CScheduler::CScheduler() :m_ios(), work(m_ios), timer_(m_ios, std::chrono::milliseconds(0)), m_pThread(nullptr), m_DuratTime(1000), m_IsStop(true), m_FunCB(nullptr), m_TimeId(0)
  4. {
  5. m_pThread = std::make_unique<std::thread>(boost::bind(&boost::asio::io_service::run, &m_ios));
  6. }
  7. CScheduler::CScheduler(boost::asio::io_service& ios) : m_ios(), work(m_ios), timer_(ios, std::chrono::milliseconds(0)), m_pThread(nullptr), m_DuratTime(1000), m_IsStop(true), m_FunCB(nullptr), m_TimeId(0)
  8. {
  9. }
  10. CScheduler::~CScheduler()
  11. {
  12. killTimer();
  13. }
  14. void CScheduler::setTimer(const std::int32_t& nIDEvent, const std::int32_t& uElapse)
  15. {
  16. if (!m_IsStop.load()) return;
  17. m_TimeId = nIDEvent;
  18. m_DuratTime = uElapse;
  19. m_IsStop.store(false);
  20. timer_.expires_from_now(std::chrono::milliseconds(m_DuratTime));
  21. timer_.async_wait(std::bind(&this_type::__onTimer, this));
  22. }
  23. void CScheduler::killTimer()
  24. {
  25. if (!m_IsStop)
  26. m_IsStop.store(true);
  27. timer_.cancel();
  28. if (m_pThread&&m_pThread->joinable()) {
  29. m_pThread->join();
  30. }
  31. }
  32. void CScheduler::setOnTimeFuncCB(FimeFunCB fun)
  33. {
  34. if (fun != nullptr&&this->m_FunCB == nullptr) {
  35. this->m_FunCB = fun;
  36. }
  37. }
  38. void CScheduler::__onTimer()
  39. {
  40. if (this->m_FunCB && !m_IsStop.load()) {
  41. this->m_FunCB(m_TimeId);
  42. }
  43. if (!m_IsStop.load()) {
  44. timer_.expires_from_now(std::chrono::milliseconds(m_DuratTime));
  45. if (!m_IsStop.load())
  46. timer_.async_wait(std::bind(&this_type::__onTimer, this));
  47. }
  48. }