功能:使用libevent实现简单定时器,每10s触发一次
流程:
代码:
//简单定时器
#include <event2/event.h>
#include <stdio.h>
#include <time.h>
#include <assert.h>
#include <signal.h>
class simple_timer final
{
public:
virtual ~simple_timer(void)
{
if (m_event_ptr != nullptr) {
event_free(m_event_ptr);
m_event_ptr = nullptr;
}
if (m_event_base_ptr != nullptr) {
event_base_free(m_event_base_ptr);
m_event_base_ptr = nullptr;
}
}
static simple_timer &get_instance(void) { static simple_timer _instance; return _instance; }
bool start(void)
{
assert(m_event_base_ptr == nullptr && m_event_ptr == nullptr);
m_event_base_ptr = event_base_new();
if (m_event_base_ptr == nullptr) {
fprintf(stderr, "ERROR failed to call event_base_new()\n");
return false;
}
m_event_ptr = event_new(m_event_base_ptr, -1, EV_PERSIST, &simple_timer::event_callback, this);
if (m_event_ptr == nullptr) {
event_base_free(m_event_base_ptr);
m_event_base_ptr = nullptr;
fprintf(stderr, "ERROR failed to call event_new() \n");
return false;
}
event_add(m_event_ptr, &m_tv);
return true;
}
void run(void)
{
event_base_dispatch(m_event_base_ptr);
}
bool stop(void)
{
if (m_event_base_ptr != nullptr);
event_base_loopbreak(m_event_base_ptr);
return true;
}
static void event_callback(int fd, short ev, void *args)
{
assert(args != nullptr);
simple_timer *self = (simple_timer *)args;
(void)(self);
fprintf(stdout, "INFO %llu time triger ! \n", (unsigned long long)time(nullptr));
}
protected:
simple_timer(void) {}
event_base *m_event_base_ptr = nullptr; //event_base指针
event *m_event_ptr = nullptr; //event_指针
timeval m_tv {10, 0}; //时间触发间隔
};
void sigterm(int sig)
{
fprintf(stdout, "INFO recv term signal !\n");
simple_timer::get_instance().stop();
}
int main(int argc, char **argv)
{
signal(SIGTERM, sigterm);
simple_timer::get_instance().start();
simple_timer::get_instance().run();
return 0;
}
|