SNode.C
Loading...
Searching...
No Matches
TimerEventReceiver.cpp
Go to the documentation of this file.
1/*
2 * SNode.C - a slim toolkit for network communication
3 * Copyright (C) Volker Christian <me@vchrist.at>
4 * 2020, 2021, 2022, 2023, 2024, 2025
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include "core/TimerEventReceiver.h"
21
22#include "core/EventLoop.h"
23#include "core/EventMultiplexer.h"
24#include "core/Timer.h"
25#include "core/TimerEventPublisher.h"
26
27#ifndef DOXYGEN_SHOULD_SKIP_THIS
28
29#include "log/Logger.h"
30
31#endif /* DOXYGEN_SHOULD_SKIP_THIS */
32
33namespace core {
34
35 TimerEventReceiver::TimerEventReceiver(const std::string& name, const utils::Timeval& delay)
36 : EventReceiver(name)
37 , timerEventPublisher(EventLoop::instance().getEventMultiplexer().getTimerEventPublisher())
38 , absoluteTimeout(utils::Timeval::currentTime() + delay)
39 , delay(delay) {
40 }
41
42 void TimerEventReceiver::restart() {
43 timerEventPublisher.erase(this);
44 absoluteTimeout = utils::Timeval::currentTime() + delay;
45 timerEventPublisher.insert(this);
46 }
47
48 TimerEventReceiver::~TimerEventReceiver() {
49 if (timer != nullptr) {
50 timer->removeTimerEventReceiver();
51 }
52 }
53
54 utils::Timeval TimerEventReceiver::getTimeoutAbsolut() const {
55 return absoluteTimeout;
56 }
57
58 utils::Timeval TimerEventReceiver::getTimeoutRelative(const utils::Timeval& currentTime) const {
59 return absoluteTimeout > currentTime ? absoluteTimeout - currentTime : 0;
60 }
61
62 void TimerEventReceiver::enable() {
63 if (core::eventLoopState() != core::State::STOPPING) {
64 timerEventPublisher.insert(this);
65 } else {
66 LOG(WARNING) << "TimerEventReceiver - Enable after signal: Not enabled";
67 delete this;
68 }
69 }
70
71 void TimerEventReceiver::update() {
72 timerEventPublisher.erase(this);
73 absoluteTimeout += delay;
74 timerEventPublisher.insert(this);
75 }
76
77 void TimerEventReceiver::cancel() {
78 timerEventPublisher.remove(this);
79 }
80
81 void TimerEventReceiver::onEvent(const utils::Timeval& currentTime) {
82 LOG(TRACE) << "TimerEventReceiver: Dispatch delta = " << (currentTime - getTimeoutAbsolut()).getMsd() << " ms";
83
84 dispatchEvent();
85 }
86
87 void TimerEventReceiver::setTimer(Timer* timer) {
88 this->timer = timer;
89 }
90
91} // namespace core