2015-09-24 20:52:02 +00:00
|
|
|
/*
|
2018-07-30 02:07:02 +00:00
|
|
|
* This is the source code of tgnet library v. 1.1
|
2015-09-24 20:52:02 +00:00
|
|
|
* It is licensed under GNU GPL v. 2 or later.
|
|
|
|
* You should have received a copy of the license in this archive (see LICENSE).
|
|
|
|
*
|
2018-07-30 02:07:02 +00:00
|
|
|
* Copyright Nikolai Kudashov, 2015-2018.
|
2015-09-24 20:52:02 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
#include "Timer.h"
|
|
|
|
#include "FileLog.h"
|
|
|
|
#include "EventObject.h"
|
|
|
|
#include "ConnectionsManager.h"
|
|
|
|
|
2018-07-30 02:07:02 +00:00
|
|
|
Timer::Timer(int32_t instance, std::function<void()> function) {
|
2015-09-24 20:52:02 +00:00
|
|
|
eventObject = new EventObject(this, EventObjectTypeTimer);
|
2018-07-30 02:07:02 +00:00
|
|
|
instanceNum = instance;
|
2015-09-24 20:52:02 +00:00
|
|
|
callback = function;
|
|
|
|
}
|
|
|
|
|
|
|
|
Timer::~Timer() {
|
|
|
|
stop();
|
|
|
|
if (eventObject != nullptr) {
|
|
|
|
delete eventObject;
|
|
|
|
eventObject = nullptr;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void Timer::start() {
|
|
|
|
if (started || timeout == 0) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
started = true;
|
2018-07-30 02:07:02 +00:00
|
|
|
ConnectionsManager::getInstance(instanceNum).scheduleEvent(eventObject, timeout);
|
2015-09-24 20:52:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void Timer::stop() {
|
|
|
|
if (!started) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
started = false;
|
2018-07-30 02:07:02 +00:00
|
|
|
ConnectionsManager::getInstance(instanceNum).removeEvent(eventObject);
|
2015-09-24 20:52:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void Timer::setTimeout(uint32_t ms, bool repeat) {
|
|
|
|
if (ms == timeout) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
repeatable = repeat;
|
|
|
|
timeout = ms;
|
|
|
|
if (started) {
|
2018-07-30 02:07:02 +00:00
|
|
|
ConnectionsManager::getInstance(instanceNum).removeEvent(eventObject);
|
|
|
|
ConnectionsManager::getInstance(instanceNum).scheduleEvent(eventObject, timeout);
|
2015-09-24 20:52:02 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void Timer::onEvent() {
|
|
|
|
callback();
|
2019-01-23 17:03:33 +00:00
|
|
|
if (LOGS_ENABLED) DEBUG_D("timer(%p) call", this);
|
2015-09-24 20:52:02 +00:00
|
|
|
if (started && repeatable && timeout != 0) {
|
2018-07-30 02:07:02 +00:00
|
|
|
ConnectionsManager::getInstance(instanceNum).scheduleEvent(eventObject, timeout);
|
2015-09-24 20:52:02 +00:00
|
|
|
}
|
|
|
|
}
|