File: SimpleTimer.h

package info (click to toggle)
asymptote 3.02%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 33,400 kB
  • sloc: cpp: 172,516; ansic: 69,728; python: 14,967; sh: 5,599; javascript: 4,866; lisp: 1,507; perl: 1,417; makefile: 1,028; yacc: 610; lex: 449; xml: 182; asm: 8
file content (49 lines) | stat: -rw-r--r-- 1,255 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#pragma once
#include <thread>
#include <atomic>
#include <functional>
#include <boost/asio.hpp>

template<typename Duration = boost::posix_time::milliseconds>
class SimpleTimer
{
public:
    SimpleTimer(unsigned int duration, std::function<void()> const& _call_back)
        : is_running_(true), call_back(_call_back), _deadline_timer(_ios, Duration(duration))
    {
        _deadline_timer.async_wait(
            [&](boost::system::error_code const& e)
            {
                if (e.value() == boost::asio::error::operation_aborted)
                {
                    return;
                }
                if (is_running_.load(std::memory_order_relaxed))
                {
                    call_back();
                }
            }
        );
        _thread = std::thread([this] { _ios.run(); });
    }
    ~SimpleTimer()
    {
        Stop();
    }
    void Stop()
    {
        is_running_.store(false, std::memory_order_relaxed);
        _ios.stop();
        if (_thread.joinable())
        {
            _thread.join();
        }
    }

private:
    std::atomic_bool is_running_;
    std::function<void()> call_back;
    boost::asio::io_context _ios;
    boost::asio::deadline_timer _deadline_timer;
    std::thread _thread;
};