Technology sharing

C timer felis

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Timor C++ regulariter Urguet, id est, omne tempus determinatum functionem exerceat

#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;
}

  • 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

compile

g++ test.cpp -lrt -lglog
  • 1