Rev | Line | |
---|
[88] | 1 | // created: 17/12/2015
|
---|
| 2 | // updated: 25/07/2016
|
---|
| 3 | // filename: CallbackTimer.h
|
---|
| 4 | //
|
---|
| 5 | // author: Milan Erdelj
|
---|
| 6 | //
|
---|
| 7 | // version: $Id: $
|
---|
| 8 | //
|
---|
| 9 | // purpose: Callback timer class (executing functions periodically)
|
---|
| 10 | //
|
---|
| 11 | //
|
---|
| 12 | /*********************************************************************/
|
---|
| 13 |
|
---|
| 14 | #ifndef CALLBACKTIMER_H
|
---|
| 15 | #define CALLBACKTIMER_H
|
---|
| 16 |
|
---|
| 17 | #include <functional>
|
---|
| 18 | #include <chrono>
|
---|
| 19 | #include <future>
|
---|
| 20 | #include <cstdio>
|
---|
| 21 | #include <iostream>
|
---|
| 22 |
|
---|
| 23 | class CallbackTimer {
|
---|
| 24 | public:
|
---|
| 25 | CallbackTimer() :_execute(false) {}
|
---|
| 26 |
|
---|
| 27 | ~CallbackTimer() {
|
---|
| 28 | if(_execute.load(std::memory_order_acquire)) {
|
---|
| 29 | stop();
|
---|
| 30 | }
|
---|
| 31 | }
|
---|
| 32 |
|
---|
| 33 | void stop() {
|
---|
| 34 | _execute.store(false, std::memory_order_release);
|
---|
| 35 | if(_thd.joinable()) _thd.join();
|
---|
| 36 | }
|
---|
| 37 |
|
---|
| 38 | void start(uint64_t interval, std::function<void(void)> callback) {
|
---|
| 39 | if(_execute.load(std::memory_order_acquire)) {
|
---|
| 40 | stop();
|
---|
| 41 | }
|
---|
| 42 | _execute.store(true, std::memory_order_release);
|
---|
| 43 | _thd = std::thread([this, interval, callback]() {
|
---|
| 44 | while (_execute.load(std::memory_order_acquire)) {
|
---|
| 45 | callback();
|
---|
| 46 | std::this_thread::sleep_for(std::chrono::microseconds(interval));
|
---|
| 47 | }
|
---|
| 48 | });
|
---|
| 49 | }
|
---|
| 50 |
|
---|
| 51 | bool is_running() const noexcept {
|
---|
| 52 | return ( _execute.load(std::memory_order_acquire) && _thd.joinable() );
|
---|
| 53 | }
|
---|
| 54 |
|
---|
| 55 | private:
|
---|
| 56 | std::atomic<bool> _execute;
|
---|
| 57 | std::thread _thd;
|
---|
| 58 | };
|
---|
| 59 |
|
---|
| 60 | #endif // CALLBACKTIMER_H
|
---|
Note:
See
TracBrowser
for help on using the repository browser.