#pragma once #include #include #include namespace Incart::Common { class JTimer : public QObject { Q_OBJECT private: int m_interval; // время в мс, через которое будет вызван timerHandler QTimer* m_timer; bool m_isRun; int m_timerTickCounter; int m_maxTickCount; QMap>> m_events; public: JTimer(int _interval, int _maxTickCount) : m_interval(_interval), m_maxTickCount(_maxTickCount) { m_timer = new QTimer(); connect(m_timer, &QTimer::timeout, this, &JTimer::HandleTimerTick); m_isRun = true; } ~JTimer() { Stop(); } public slots: // Обработка таймера void HandleTimerTick() { if (!m_isRun) { m_timer->stop(); delete m_timer; m_timer = nullptr; return; } m_timerTickCounter++; if (m_timerTickCounter == m_maxTickCount) { m_timerTickCounter = 0; } for (auto it = m_events.begin(); it != m_events.end(); it++) { if (m_timerTickCounter % it.key() == 0) { QList>* tickEvents = &it.value(); for (auto it2 = tickEvents->begin(); it2 != tickEvents->end(); it2++) { (*it2).second((*it2).first); } } } } public: void AddEvent(int _tickCount, void* _sender, void (*_action)(void*)) { m_events[_tickCount].append(QPair(_sender, _action)); } void RemoveEvent(void* _sender) { disconnect(m_timer, &QTimer::timeout, this, &JTimer::HandleTimerTick); for (auto it = m_events.begin(); it != m_events.end(); it++) { QList>* tickEvents = &it.value(); for (int i = tickEvents->length() - 1; i >= 0; i--) { if (_sender == (*tickEvents)[i].first) { tickEvents->removeAt(i); } } } connect(m_timer, &QTimer::timeout, this, &JTimer::HandleTimerTick); } void Start() { if (m_timer != nullptr) { m_timer->start(m_interval); } } void Stop() { if (m_timer != nullptr) { m_timer->stop(); delete m_timer; m_timer = nullptr; } } }; } // namespace Incart::Common