2 Copyright (c) 2018-2019 Nokia.
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
18 * This source code is part of the near-RT RIC (RAN Intelligent Controller)
19 * platform project (RICP).
22 #include "private/timerfd.hpp"
23 #include "private/engine.hpp"
24 #include "private/system.hpp"
26 using namespace shareddatalayer;
28 TimerFD::TimerFD(Engine& engine):
29 TimerFD(System::getSystem(), engine)
33 TimerFD::TimerFD(System& system, Engine& engine):
35 fd(system, system.timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC))
37 engine.addMonitoredFD(fd, Engine::EVENT_IN, std::bind(&TimerFD::handleEvents, this));
44 void TimerFD::arm(Timer& timer, const Timer::Duration& duration, const Timer::Callback& cb)
46 const auto absolute(toAbsolute(duration));
47 const auto i(queue.insert(std::make_pair(absolute, std::make_pair(&timer, cb))));
53 bool TimerFD::isFirst(Queue::iterator it) const
55 return queue.begin() == it;
58 void TimerFD::disarm(const Timer& timer)
60 const bool wasFirst(isFirst(timer.iterator));
61 queue.erase(timer.iterator);
66 armTimerFD(nextTrigger());
69 Timer::Duration TimerFD::toAbsolute(const Timer::Duration& duration)
71 return std::chrono::duration_cast<Timer::Duration>(system.time_since_epoch()) + duration;
74 void TimerFD::handleEvents()
77 handleExpiredTimers();
80 bool TimerFD::timerExpired() const
83 return (system.read(fd, &count, sizeof(count)) == sizeof(count)) && (count > 0U);
86 void TimerFD::handleExpiredTimers()
88 const auto now(system.time_since_epoch());
91 popAndExecuteFirstTimer();
98 while (queue.begin()->first <= now);
99 armTimerFD(nextTrigger());
102 void TimerFD::popAndExecuteFirstTimer()
104 const auto i(queue.begin());
105 const auto cb(i->second.second);
110 Timer::Duration TimerFD::nextTrigger() const
112 return queue.begin()->first;
115 void TimerFD::disarmTimerFD()
117 setTimeForTimerFD(0, 0);
120 void TimerFD::armTimerFD(const Timer::Duration& duration)
122 static const long int NANOSECONDS_IN_ONE_SECOND(1E9);
123 setTimeForTimerFD(std::chrono::duration_cast<std::chrono::seconds>(duration).count(),
124 std::chrono::duration_cast<std::chrono::nanoseconds>(duration).count() % NANOSECONDS_IN_ONE_SECOND);
127 void TimerFD::setTimeForTimerFD(time_t seconds, long int nanoseconds)
129 const itimerspec ts{ { 0, 0 }, { seconds, nanoseconds } };
130 system.timerfd_settime(fd, TFD_TIMER_ABSTIME, &ts, nullptr);