0.4.1
Loading...
Searching...
No Matches
CallbackTimer.cpp
Go to the documentation of this file.
1// This file is part of INSTINCT, the INS Toolkit for Integrated
2// Navigation Concepts and Training by the Institute of Navigation of
3// the University of Stuttgart, Germany.
4//
5// This Source Code Form is subject to the terms of the Mozilla Public
6// License, v. 2.0. If a copy of the MPL was not distributed with this
7// file, You can obtain one at https://mozilla.org/MPL/2.0/.
8
9#include "CallbackTimer.hpp"
10
11#include <chrono>
12
14{
15 if (_execute.load(std::memory_order_acquire))
16 {
17 stop();
18 };
19}
20
22{
23 _execute.store(false, std::memory_order_release);
24 if (_thd.joinable())
25 {
26 _thd.join();
27 }
28}
29
30void CallbackTimer::start(int interval, const std::function<void(void*)>& func, void* userData)
31{
32 if (_execute.load(std::memory_order_acquire))
33 {
34 stop();
35 };
36 _interval.store(interval, std::memory_order_release);
37 _execute.store(true, std::memory_order_release);
38 _thd = std::thread([this, func, userData]() {
39 while (_execute.load(std::memory_order_acquire))
40 {
41 auto start = std::chrono::steady_clock::now();
42 func(userData);
43 // std::this_thread::sleep_for(
44 // std::chrono::milliseconds(_interval));
45
46 std::this_thread::sleep_until(start + std::chrono::milliseconds(_interval.load(std::memory_order_acquire)));
47 }
48 });
49}
50
52{
53 _interval.store(interval, std::memory_order_release);
54}
55
56bool CallbackTimer::is_running() const noexcept
57{
58 return (_execute.load(std::memory_order_acquire) && _thd.joinable());
59}
Starts a Periodic Timer.
~CallbackTimer()
Destructor.
std::atomic< bool > _execute
Flag whether the timer should execute.
std::thread _thd
Thread object which triggers the timer.
void setInterval(int interval)
Set the Interval of the timer.
void start(int interval, const std::function< void(void *)> &func, void *userData)
Starts the timer.
void stop()
Stops the Timer.
std::atomic< int > _interval
Interval in which the timer is triggered.
bool is_running() const noexcept
Checks if the timer is currently running.