Timer.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * This is the source code of tgnet library v. 1.1
  3. * It is licensed under GNU GPL v. 2 or later.
  4. * You should have received a copy of the license in this archive (see LICENSE).
  5. *
  6. * Copyright Nikolai Kudashov, 2015-2018.
  7. */
  8. #include "Timer.h"
  9. #include "FileLog.h"
  10. #include "EventObject.h"
  11. #include "ConnectionsManager.h"
  12. Timer::Timer(int32_t instance, std::function<void()> function) {
  13. eventObject = new EventObject(this, EventObjectTypeTimer);
  14. instanceNum = instance;
  15. callback = function;
  16. }
  17. Timer::~Timer() {
  18. stop();
  19. if (eventObject != nullptr) {
  20. delete eventObject;
  21. eventObject = nullptr;
  22. }
  23. }
  24. void Timer::start() {
  25. if (started || timeout == 0) {
  26. return;
  27. }
  28. started = true;
  29. ConnectionsManager::getInstance(instanceNum).scheduleEvent(eventObject, timeout);
  30. }
  31. void Timer::stop() {
  32. if (!started) {
  33. return;
  34. }
  35. started = false;
  36. ConnectionsManager::getInstance(instanceNum).removeEvent(eventObject);
  37. }
  38. void Timer::setTimeout(uint32_t ms, bool repeat) {
  39. if (ms == timeout) {
  40. return;
  41. }
  42. repeatable = repeat;
  43. timeout = ms;
  44. if (started) {
  45. ConnectionsManager::getInstance(instanceNum).removeEvent(eventObject);
  46. ConnectionsManager::getInstance(instanceNum).scheduleEvent(eventObject, timeout);
  47. }
  48. }
  49. void Timer::onEvent() {
  50. callback();
  51. if (LOGS_ENABLED) DEBUG_D("timer(%p) call", this);
  52. if (started && repeatable && timeout != 0) {
  53. ConnectionsManager::getInstance(instanceNum).scheduleEvent(eventObject, timeout);
  54. }
  55. }