LCOV - code coverage report
Current view: top level - common/source - Timer.cpp (source / functions) Coverage Total Hit
Test: coverage.info Lines: 94.8 % 96 91
Test Date: 2026-11-10 16:58:19 Functions: 100.0 % 16 16

            Line data    Source code
       1              : /*
       2              :  * If not stated otherwise in this file or this component's LICENSE file the
       3              :  * following copyright and licenses apply:
       4              :  *
       5              :  * Copyright 2022 Sky UK
       6              :  *
       7              :  * Licensed under the Apache License, Version 2.0 (the "License");
       8              :  * you may not use this file except in compliance with the License.
       9              :  * You may obtain a copy of the License at
      10              :  *
      11              :  * http://www.apache.org/licenses/LICENSE-2.0
      12              :  *
      13              :  * Unless required by applicable law or agreed to in writing, software
      14              :  * distributed under the License is distributed on an "AS IS" BASIS,
      15              :  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      16              :  * See the License for the specific language governing permissions and
      17              :  * limitations under the License.
      18              :  */
      19              : 
      20              : #include "Timer.h"
      21              : #include "RialtoCommonLogging.h"
      22              : #include <atomic>
      23              : #include <chrono>
      24              : #include <condition_variable>
      25              : #include <functional>
      26              : #include <mutex>
      27              : #include <queue>
      28              : #include <thread>
      29              : #include <unordered_map>
      30              : 
      31              : namespace
      32              : {
      33              : class CommonTimerLoop
      34              : {
      35              : public:
      36              :     using Clock = std::chrono::steady_clock;
      37              :     using Duration = std::chrono::milliseconds;
      38              :     using Callback = std::function<void()>;
      39              : 
      40           30 :     static CommonTimerLoop &instance()
      41              :     {
      42           30 :         static CommonTimerLoop instance;
      43           30 :         return instance;
      44              :     }
      45              : 
      46              : private:
      47              :     struct TimerTask
      48              :     {
      49              :         std::uint64_t id;
      50              :         Clock::time_point nextExecution;
      51              :         Duration interval;
      52              :         Callback callback;
      53              :         bool repeat;
      54              :         std::atomic<bool> cancelled{false};
      55              :     };
      56              : 
      57              :     struct Compare
      58              :     {
      59            1 :         bool operator()(const std::shared_ptr<TimerTask> &a, const std::shared_ptr<TimerTask> &b) const
      60              :         {
      61            1 :             return a->nextExecution > b->nextExecution;
      62              :         }
      63              :     };
      64              : 
      65              :     std::priority_queue<std::shared_ptr<TimerTask>, std::vector<std::shared_ptr<TimerTask>>, Compare> m_tasks;
      66              : 
      67              :     std::unordered_map<std::uint64_t, std::shared_ptr<TimerTask>> m_activeTasks;
      68              : 
      69              :     std::mutex m_mutex;
      70              :     std::condition_variable m_cv;
      71              : 
      72              :     std::thread m_worker;
      73              :     std::atomic<bool> m_running{true};
      74              : 
      75              :     std::atomic<std::uint64_t> m_nextId{1};
      76              : 
      77            1 :     CommonTimerLoop()
      78            1 :     {
      79            1 :         RIALTO_COMMON_LOG_DEBUG("Starting CommonTimerLoop");
      80            2 :         m_worker = std::thread([this]() { run(); });
      81            1 :     }
      82              : 
      83            1 :     ~CommonTimerLoop()
      84            1 :     {
      85            1 :         if (!m_running.exchange(false))
      86            0 :             return;
      87              : 
      88            1 :         m_cv.notify_one();
      89              : 
      90            1 :         if (m_worker.joinable())
      91            1 :             m_worker.join();
      92              : 
      93            1 :         RIALTO_COMMON_LOG_DEBUG("CommonTimerLoop stopped");
      94              :     }
      95              : 
      96              :     CommonTimerLoop(const CommonTimerLoop &) = delete;
      97              :     CommonTimerLoop &operator=(const CommonTimerLoop &) = delete;
      98              :     CommonTimerLoop(CommonTimerLoop &&) = delete;
      99              :     CommonTimerLoop &operator=(CommonTimerLoop &&) = delete;
     100              : 
     101              : public:
     102            8 :     std::uint64_t add(Duration delay, Callback callback, firebolt::rialto::common::TimerType timerType)
     103              :     {
     104            8 :         auto task = std::make_shared<TimerTask>();
     105              : 
     106            8 :         task->id = m_nextId++;
     107            8 :         task->nextExecution = Clock::now() + delay;
     108            8 :         task->interval = delay;
     109            8 :         task->callback = std::move(callback);
     110            8 :         task->repeat = timerType == firebolt::rialto::common::TimerType::PERIODIC;
     111              : 
     112              :         {
     113            8 :             std::lock_guard<std::mutex> lock(m_mutex);
     114              : 
     115            8 :             m_activeTasks[task->id] = task;
     116            8 :             m_tasks.push(task);
     117              :         }
     118              : 
     119            8 :         m_cv.notify_one();
     120              : 
     121           16 :         return task->id;
     122            8 :     }
     123              : 
     124           13 :     void cancel(std::uint64_t id)
     125              :     {
     126           13 :         std::lock_guard<std::mutex> lock(m_mutex);
     127              : 
     128           13 :         auto it = m_activeTasks.find(id);
     129              : 
     130           13 :         if (it != m_activeTasks.end())
     131              :         {
     132            4 :             it->second->cancelled = true;
     133            4 :             m_activeTasks.erase(it);
     134              :         }
     135              : 
     136           13 :         m_cv.notify_one();
     137              :     }
     138              : 
     139            9 :     bool isActive(std::uint64_t id)
     140              :     {
     141            9 :         std::lock_guard<std::mutex> lock(m_mutex);
     142           18 :         return m_activeTasks.find(id) != m_activeTasks.end();
     143            9 :     }
     144              : 
     145              : private:
     146            1 :     void run()
     147              :     {
     148            1 :         std::unique_lock<std::mutex> lock(m_mutex);
     149              : 
     150           34 :         while (m_running)
     151              :         {
     152              :             // remove cancelled tasks from the top of the queue
     153           36 :             while (!m_tasks.empty() && m_tasks.top()->cancelled)
     154            3 :                 m_tasks.pop();
     155              : 
     156           33 :             if (m_tasks.empty())
     157              :             {
     158           24 :                 m_cv.wait(lock, [this]() { return !m_running || !m_tasks.empty(); });
     159              : 
     160           21 :                 continue;
     161            7 :             }
     162              : 
     163           26 :             auto task = m_tasks.top();
     164              : 
     165           26 :             auto now = Clock::now();
     166              : 
     167           26 :             if (task->nextExecution > now)
     168              :             {
     169           14 :                 m_cv.wait_until(lock, task->nextExecution);
     170           14 :                 continue;
     171              :             }
     172              : 
     173           12 :             m_tasks.pop();
     174              : 
     175           12 :             if (task->cancelled)
     176            0 :                 continue;
     177              : 
     178           12 :             if (!task->repeat)
     179            4 :                 m_activeTasks.erase(task->id);
     180              : 
     181           12 :             lock.unlock();
     182              : 
     183              :             try
     184              :             {
     185           12 :                 task->callback();
     186              :             }
     187            1 :             catch (...)
     188              :             {
     189            1 :                 RIALTO_COMMON_LOG_ERROR("Exception occurred while executing timer callback");
     190              :             }
     191              : 
     192           12 :             lock.lock();
     193              : 
     194           12 :             if (m_running && task->repeat && !task->cancelled)
     195              :             {
     196            7 :                 task->nextExecution = Clock::now() + task->interval;
     197            7 :                 m_tasks.push(task);
     198              :             }
     199              :             else
     200              :             {
     201            5 :                 m_activeTasks.erase(task->id);
     202              :             }
     203           26 :         }
     204              : 
     205            1 :         while (!m_tasks.empty())
     206            0 :             m_tasks.pop();
     207              : 
     208            1 :         m_activeTasks.clear();
     209              :     }
     210              : };
     211              : } // namespace
     212              : 
     213              : namespace firebolt::rialto::common
     214              : {
     215              : std::weak_ptr<ITimerFactory> TimerFactory::m_factory;
     216              : 
     217           35 : std::shared_ptr<ITimerFactory> ITimerFactory::getFactory()
     218              : {
     219           35 :     std::shared_ptr<ITimerFactory> factory = TimerFactory::m_factory.lock();
     220              : 
     221           35 :     if (!factory)
     222              :     {
     223              :         try
     224              :         {
     225           35 :             factory = std::make_shared<TimerFactory>();
     226              :         }
     227            0 :         catch (const std::exception &e)
     228              :         {
     229            0 :             RIALTO_COMMON_LOG_ERROR("Failed to create the timer factory, reason: %s", e.what());
     230              :         }
     231              : 
     232           35 :         TimerFactory::m_factory = factory;
     233              :     }
     234              : 
     235           35 :     return factory;
     236              : }
     237              : 
     238            9 : std::unique_ptr<ITimer> TimerFactory::createTimer(const std::chrono::milliseconds &timeout,
     239              :                                                   const std::function<void()> &callback, TimerType timerType) const
     240              : {
     241            9 :     return std::make_unique<Timer>(timeout, callback, timerType);
     242              : }
     243              : 
     244            9 : Timer::Timer(const std::chrono::milliseconds &timeout, const std::function<void()> &callback, TimerType timerType)
     245              : {
     246            9 :     if (!callback)
     247              :     {
     248            1 :         RIALTO_COMMON_LOG_ERROR("Timer callback is not set");
     249            1 :         return;
     250              :     }
     251            8 :     m_id = CommonTimerLoop::instance().add(timeout, callback, timerType);
     252              : }
     253              : 
     254           18 : Timer::~Timer()
     255              : {
     256            9 :     cancel();
     257           18 : }
     258              : 
     259           13 : void Timer::cancel()
     260              : {
     261           13 :     CommonTimerLoop::instance().cancel(m_id);
     262              : }
     263              : 
     264            9 : bool Timer::isActive() const
     265              : {
     266            9 :     return CommonTimerLoop::instance().isActive(m_id);
     267              : }
     268              : } // namespace firebolt::rialto::common
        

Generated by: LCOV version 2.0-1