Bootstrap

C++ 定时器触发

c++定时器,能够定时触发,即每隔一段固定时间执行一下函数

#include <iostream>
#include <thread>
#include <chrono>
#include <signal.h>
#include <time.h>
#include <cstring>
#include <glog/logging.h>

#define EVENTSAVERTIMER_SIG (SIGRTMIN + 14)   // 设置信号
#define EvensTimerPeriod (5) // 5ms

// 定时器处理函数
void timerHandler(int sig, siginfo_t *si, void *uc) {
    LOG(ERROR) << "Timer triggered!" << std::endl;
}

void EventSaverTimerInit(void)
{

	/*配置一个Posix timer*/
	timer_t TimerPulse;
	struct sigevent Timer1_Pulse_Sig;
	struct sigaction Timer1_Pulse_Sa;
	struct itimerspec Timer1_Pulse_it; // 匹配pulse类型定时器1 的timer设定参数
	int res;

	Timer1_Pulse_Sa.sa_flags = SA_SIGINFO | SA_RESTART;
	Timer1_Pulse_Sa.sa_sigaction = timerHandler;
	sigemptyset(&Timer1_Pulse_Sa.sa_mask);
	if (sigaction(EVENTSAVERTIMER_SIG, &Timer1_Pulse_Sa, NULL) == -1)
	{
		perror("sigaction");
	}

	memset(&Timer1_Pulse_Sig, 0, sizeof(Timer1_Pulse_Sig));

	// 信号量配置
	Timer1_Pulse_Sig.sigev_value.sival_ptr = &TimerPulse;
	Timer1_Pulse_Sig.sigev_notify = SIGEV_SIGNAL;
	Timer1_Pulse_Sig.sigev_signo = EVENTSAVERTIMER_SIG;

	res = timer_create(CLOCK_REALTIME, &Timer1_Pulse_Sig, &TimerPulse);
	if (res != 0)
	{
		perror("TimerPulse create Error");
		return;
	}

	Timer1_Pulse_it.it_value.tv_sec = 0; // 定时器第一次触发的时间, 启动延时时间 5 ms
	Timer1_Pulse_it.it_value.tv_nsec = 5 * 1000 * 1000;
	Timer1_Pulse_it.it_interval.tv_sec = 0;								  // timer周期
	Timer1_Pulse_it.it_interval.tv_nsec = EvensTimerPeriod * 1000 * 1000; // 10 ms, 纳秒,微秒,毫秒,秒
	/*结束配置一个Poisix timer*/

	res = timer_settime(TimerPulse, 0, &Timer1_Pulse_it, NULL);
	if (res)
	{
		perror("TimerPulse settime Error");
		return;
	}
}

int main() {
    // startTimer();
    EventSaverTimerInit();

    // 主线程继续执行其他操作
    for (int i = 0; i < 100; ++i) {
        // std::cout << "Main thread doing work: " << i << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    // 关闭glog
    google::ShutdownGoogleLogging();
    return 0;
}

编译

g++ test.cpp -lrt -lglog
;