The Gaudi Framework  master (181af51f)
Loading...
Searching...
No Matches
PeriodicAction.cpp
Go to the documentation of this file.
1/***********************************************************************************\
2* (c) Copyright 2024-2025 CERN for the benefit of the LHCb and ATLAS collaborations *
3* *
4* This software is distributed under the terms of the Apache version 2 licence, *
5* copied verbatim in the file "LICENSE". *
6* *
7* In applying this licence, CERN does not waive the privileges and immunities *
8* granted to it by virtue of its status as an Intergovernmental Organization *
9* or submit itself to any jurisdiction. *
10\***********************************************************************************/
12#include <utility>
13
15
16PeriodicAction::PeriodicAction( callback_t callback, std::chrono::milliseconds period_duration, bool autostart )
17 : m_callback{ std::move( callback ) }, m_period_duration{ period_duration } {
18 if ( autostart ) start();
19}
20
22
24 if ( !m_thread.joinable() && m_period_duration.count() > 0 ) {
25 // Note: we can move the callback because we are not going to use it
26 // outside of the thread
27 m_thread = std::thread{ [period_duration = m_period_duration, callback = std::move( m_callback ),
28 stop_signal = m_stop_thread.get_future()] {
29 auto next_call = clock::now() + period_duration;
30 while ( stop_signal.wait_until( next_call ) == std::future_status::timeout ) {
31 callback();
32 // ensure the next call is at a multiple
33 // of m_period_duration after the last one
34 const auto now = clock::now();
35 while ( next_call < now ) next_call += period_duration;
36 }
37 } };
38 }
39}
40
42 if ( m_thread.joinable() ) {
43 m_stop_thread.set_value();
44 m_thread.join();
45 }
46}
Helper to periodically run asynchronous tasks.
std::chrono::milliseconds m_period_duration
std::promise< void > m_stop_thread
std::function< void()> callback_t
PeriodicAction(callback_t callback, std::chrono::milliseconds period_duration, bool autostart=true)
STL namespace.