1在Linux中,timer_create
是一个用于创建定时器的系统调用。它允许你创建一个POSIX定时器,用于在未来的某个时间点触发信号或执行回调函数。
例如:
my_time.h
#ifndef _SELF_TIMER_H_
#define _SELF_TIMER_H_
#include <unistd.h>
#include <signal.h>
#include <time.h>
typedef struct sigevent SIG_EVENT;
typedef struct itimerspec ITIMER_SPEC;
class Timers{
public:
Timers();
~Timers();
void set_timer(SIG_EVENT,ITIMER_SPEC);
void create_timer();
void destory_timer();
public:
typedef void (*TimerHandler)(union sigval);
private:
TimerHandler m_handle;
timer_t m_timer;
SIG_EVENT m_sev;
ITIMER_SPEC m_its;
};
#endif
my_time.cpp
#include "self_timer.h"
Timers::Timers(){}
Timers::~Timers(){}
void Timers::set_timer(SIG_EVENT sev,ITIMER_SPEC its)
{
if(sev.sigev_notify == SIGEV_THREAD){
m_sev.sigev_notify_function = sev.sigev_notify_function; // 处理函数
}
else if(sev.sigev_notify == SIGEV_SIGNAL){
m_sev.sigev_signo = sev.sigev_signo; // 要发送的信号编号,提前注册对应的信号的处理函数
}
// 创建定时器
m_sev.sigev_notify = sev.sigev_notify;
m_sev.sigev_value.sival_ptr = &m_timer;
m_sev.sigev_notify_attributes = sev.sigev_notify_attributes;
// 设置定时器参数
m_its.it_interval.tv_sec = its.it_interval.tv_sec; // 定时器间隔:x秒
m_its.it_interval.tv_nsec = its.it_interval.tv_nsec;
m_its.it_value.tv_sec = its.it_value.tv_sec; // 第一次触发时间:x秒后
m_its.it_value.tv_nsec = its.it_value.tv_nsec;
}
void Timers::create_timer()
{
timer_create(CLOCK_REALTIME, &m_sev, &m_timer);
timer_settime(m_timer, 0, &m_its, NULL);
}
void Timers::destory_timer()
{
// 销毁定时器
timer_delete(m_timer);
}