Created
September 13, 2018 15:51
-
-
Save klopp/46b2205164704c8f085c6e8e678ae657 to your computer and use it in GitHub Desktop.
Periodic timer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class lp_timer_t { | |
private: | |
timer_t timerid; | |
bool started; | |
void* data; | |
struct sigevent sev; | |
struct sigaction sa; | |
struct sigaction prev; | |
struct itimerspec its; | |
protected: | |
static void on_timer(int sig, siginfo_t *si, void *uc) { | |
lp_timer_t * t = reinterpret_cast<lp_timer_t *>(si->si_value.sival_ptr); | |
t->on_timer(t->data); | |
} | |
public: | |
lp_timer_t() : timerid(0), started(false), data(nullptr) { | |
}; | |
virtual ~lp_timer_t() { | |
stop(); | |
} | |
void start(uint32_t seconds, void* ptr = nullptr) { | |
if(!started && seconds) { | |
data = ptr; | |
sigaction(SIGRTMIN, NULL, &prev); | |
sa.sa_flags = SA_SIGINFO; | |
sa.sa_sigaction = on_timer; | |
sigemptyset(&sa.sa_mask); | |
sigaction(SIGRTMIN, &sa, NULL); | |
sev.sigev_notify = SIGEV_SIGNAL; | |
sev.sigev_signo = SIGRTMIN; | |
sev.sigev_value.sival_ptr = this; | |
timer_create(CLOCK_MONOTONIC, &sev, &timerid); | |
its.it_value.tv_sec = 0; | |
its.it_value.tv_nsec = 1; | |
its.it_interval.tv_sec = seconds; | |
its.it_interval.tv_nsec = 0; | |
timer_settime(timerid, 0, &its, NULL); | |
started = true; | |
} | |
} | |
void stop() { | |
if(started) { | |
timer_delete(timerid); | |
sigaction(SIGRTMIN, &prev, NULL); | |
started = false; | |
} | |
} | |
virtual void on_timer(void* data) = 0; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment