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.
17 #include "private/timerfd.hpp"
18 #include "private/engine.hpp"
19 #include "private/system.hpp"
21 using namespace shareddatalayer;
23 TimerFD::TimerFD(Engine& engine):
24 TimerFD(System::getSystem(), engine)
28 TimerFD::TimerFD(System& system, Engine& engine):
30 fd(system, system.timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC))
32 engine.addMonitoredFD(fd, Engine::EVENT_IN, std::bind(&TimerFD::handleEvents, this));
39 void TimerFD::arm(Timer& timer, const Timer::Duration& duration, const Timer::Callback& cb)
41 const auto absolute(toAbsolute(duration));
42 const auto i(queue.insert(std::make_pair(absolute, std::make_pair(&timer, cb))));
48 bool TimerFD::isFirst(Queue::iterator it) const
50 return queue.begin() == it;
53 void TimerFD::disarm(const Timer& timer)
55 const bool wasFirst(isFirst(timer.iterator));
56 queue.erase(timer.iterator);
61 armTimerFD(nextTrigger());
64 Timer::Duration TimerFD::toAbsolute(const Timer::Duration& duration)
66 return std::chrono::duration_cast<Timer::Duration>(system.time_since_epoch()) + duration;
69 void TimerFD::handleEvents()
72 handleExpiredTimers();
75 bool TimerFD::timerExpired() const
78 return (system.read(fd, &count, sizeof(count)) == sizeof(count)) && (count > 0U);
81 void TimerFD::handleExpiredTimers()
83 const auto now(system.time_since_epoch());
86 popAndExecuteFirstTimer();
93 while (queue.begin()->first <= now);
94 armTimerFD(nextTrigger());
97 void TimerFD::popAndExecuteFirstTimer()
99 const auto i(queue.begin());
100 const auto cb(i->second.second);
105 Timer::Duration TimerFD::nextTrigger() const
107 return queue.begin()->first;
110 void TimerFD::disarmTimerFD()
112 setTimeForTimerFD(0, 0);
115 void TimerFD::armTimerFD(const Timer::Duration& duration)
117 static const long int NANOSECONDS_IN_ONE_SECOND(1E9);
118 setTimeForTimerFD(std::chrono::duration_cast<std::chrono::seconds>(duration).count(),
119 std::chrono::duration_cast<std::chrono::nanoseconds>(duration).count() % NANOSECONDS_IN_ONE_SECOND);
122 void TimerFD::setTimeForTimerFD(time_t seconds, long int nanoseconds)
124 const itimerspec ts{ { 0, 0 }, { seconds, nanoseconds } };
125 system.timerfd_settime(fd, TFD_TIMER_ABSTIME, &ts, nullptr);