summaryrefslogtreecommitdiffstats
path: root/example/heartbeat.cpp
blob: f7390d77c4152d7a3087d199bc310909c36cde3a (plain)
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
50
51
#include <chrono>
#include <cstdio>
#include <sdeventplus/clock.hpp>
#include <sdeventplus/event.hpp>
#include <sdeventplus/source/signal.hpp>
#include <sdeventplus/source/time.hpp>
#include <stdplus/signal.hpp>
#include <string>
#include <utility>

using sdeventplus::Event;
using sdeventplus::source::Enabled;
using sdeventplus::source::Signal;

constexpr auto clockId = sdeventplus::ClockId::RealTime;
using Clock = sdeventplus::Clock<clockId>;
using Time = sdeventplus::source::Time<clockId>;

void intCb(Signal& signal, const struct signalfd_siginfo*)
{
    printf("Exiting\n");
    signal.get_event().exit(0);
}

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s [seconds]\n", argv[0]);
        return 1;
    }

    unsigned interval = std::stoul(argv[1]);
    fprintf(stderr, "Beating every %u seconds\n", interval);

    auto event = Event::get_default();
    auto hbFunc = [interval](Time& source, Time::TimePoint time) {
        printf("Beat\n");

        // Time sources are oneshot and are based on an absolute time
        // we need to reconfigure the time source to go off again after the
        // configured interval and re-enable it.
        source.set_time(time + std::chrono::seconds{interval});
        source.set_enabled(Enabled::OneShot);
    };
    Time time(event, Clock(event).now(), std::chrono::seconds{1},
              std::move(hbFunc));
    stdplus::signal::block(SIGINT);
    Signal signal(event, SIGINT, intCb);
    return event.loop();
}
OpenPOWER on IntegriCloud