#include "stdafx.h" #include "Scheduler.h" 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) { m_pThread = std::make_unique(boost::bind(&boost::asio::io_service::run, &m_ios)); } 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) { } CScheduler::~CScheduler() { killTimer(); } void CScheduler::setTimer(const std::int32_t& nIDEvent, const std::int32_t& uElapse) { if (!m_IsStop.load()) return; m_TimeId = nIDEvent; m_DuratTime = uElapse; m_IsStop.store(false); timer_.expires_from_now(std::chrono::milliseconds(m_DuratTime)); timer_.async_wait(std::bind(&this_type::__onTimer, this)); } void CScheduler::killTimer() { if (!m_IsStop) m_IsStop.store(true); timer_.cancel(); if (m_pThread&&m_pThread->joinable()) { m_pThread->join(); } } void CScheduler::setOnTimeFuncCB(FimeFunCB fun) { if (fun != nullptr&&this->m_FunCB == nullptr) { this->m_FunCB = fun; } } void CScheduler::__onTimer() { if (this->m_FunCB && !m_IsStop.load()) { this->m_FunCB(m_TimeId); } if (!m_IsStop.load()) { timer_.expires_from_now(std::chrono::milliseconds(m_DuratTime)); if (!m_IsStop.load()) timer_.async_wait(std::bind(&this_type::__onTimer, this)); } }