forked from berndporr/cppTimer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCppTimer.h
More file actions
93 lines (77 loc) · 1.93 KB
/
CppTimer.h
File metadata and controls
93 lines (77 loc) · 1.93 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#ifndef __CPP_TIMER_H_
#define __CPP_TIMER_H_
/**
* GNU GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* (C) 2020, Bernd Porr <[email protected]>
*
* This is inspired by the timer_create man page.
**/
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#define CLOCKID CLOCK_MONOTONIC
#define SIG SIGRTMIN
/**
* Enumeration of CppTimer types
**/
typedef enum cppTimerType_t{
PERIODIC,
ONESHOT
}cppTimerType_t;
/**
* Timer class which repeatedly fires. It's wrapper around the
* POSIX per-process timer.
**/
class CppTimer {
public:
/**
* Creates an instance of the timer and connects the
* signal handler to the timer.
**/
CppTimer();
/**
* Starts the timer. The timer fires first after
* the specified time in nanoseconds and then at
* that interval in PERIODIC mode. In ONESHOT mode
* the timer fires once after the specified time in
* nanoseconds.
**/
virtual void start(long nanosecs, cppTimerType_t type = PERIODIC);
/**
* Starts the timer. The timer fires first after
* the specified time in milliseconds and then at
* that interval in PERIODIC mode. In ONESHOT mode
* the timer fires once after the specified time in
* milliseconds.
**/
virtual void startms(long millisecs, cppTimerType_t type = PERIODIC);
/**
* Stops the timer by disarming it. It can be re-started
* with start().
**/
virtual void stop();
/**
* Destructor disarms the timer, deletes it and
* disconnect the signal handler.
**/
virtual ~CppTimer();
protected:
/**
* Abstract function which needs to be implemented by the children.
* This is called every time the timer fires.
**/
virtual void timerEvent() = 0;
private:
timer_t timerid = 0;
struct sigevent sev;
struct sigaction sa;
struct itimerspec its;
static void handler(int sig, siginfo_t *si, void *uc ) {
(reinterpret_cast<CppTimer *> (si->si_value.sival_ptr))->timerEvent();
}
};
#endif