C++ 定时器触发

打印 上一主题 下一主题

主题 544|帖子 544|积分 1632

c++定时器,能够定时触发,即每隔一段固定时间实行一下函数
  1. #include <iostream>
  2. #include <thread>
  3. #include <chrono>
  4. #include <signal.h>
  5. #include <time.h>
  6. #include <cstring>
  7. #include <glog/logging.h>
  8. #define EVENTSAVERTIMER_SIG (SIGRTMIN + 14)   // 设置信号
  9. #define EvensTimerPeriod (5) // 5ms
  10. // 定时器处理函数
  11. void timerHandler(int sig, siginfo_t *si, void *uc) {
  12.     LOG(ERROR) << "Timer triggered!" << std::endl;
  13. }
  14. void EventSaverTimerInit(void)
  15. {
  16.         /*配置一个Posix timer*/
  17.         timer_t TimerPulse;
  18.         struct sigevent Timer1_Pulse_Sig;
  19.         struct sigaction Timer1_Pulse_Sa;
  20.         struct itimerspec Timer1_Pulse_it; // 匹配pulse类型定时器1 的timer设定参数
  21.         int res;
  22.         Timer1_Pulse_Sa.sa_flags = SA_SIGINFO | SA_RESTART;
  23.         Timer1_Pulse_Sa.sa_sigaction = timerHandler;
  24.         sigemptyset(&Timer1_Pulse_Sa.sa_mask);
  25.         if (sigaction(EVENTSAVERTIMER_SIG, &Timer1_Pulse_Sa, NULL) == -1)
  26.         {
  27.                 perror("sigaction");
  28.         }
  29.         memset(&Timer1_Pulse_Sig, 0, sizeof(Timer1_Pulse_Sig));
  30.         // 信号量配置
  31.         Timer1_Pulse_Sig.sigev_value.sival_ptr = &TimerPulse;
  32.         Timer1_Pulse_Sig.sigev_notify = SIGEV_SIGNAL;
  33.         Timer1_Pulse_Sig.sigev_signo = EVENTSAVERTIMER_SIG;
  34.         res = timer_create(CLOCK_REALTIME, &Timer1_Pulse_Sig, &TimerPulse);
  35.         if (res != 0)
  36.         {
  37.                 perror("TimerPulse create Error");
  38.                 return;
  39.         }
  40.         Timer1_Pulse_it.it_value.tv_sec = 0; // 定时器第一次触发的时间, 启动延时时间 5 ms
  41.         Timer1_Pulse_it.it_value.tv_nsec = 5 * 1000 * 1000;
  42.         Timer1_Pulse_it.it_interval.tv_sec = 0;                                                                  // timer周期
  43.         Timer1_Pulse_it.it_interval.tv_nsec = EvensTimerPeriod * 1000 * 1000; // 10 ms, 纳秒,微秒,毫秒,秒
  44.         /*结束配置一个Poisix timer*/
  45.         res = timer_settime(TimerPulse, 0, &Timer1_Pulse_it, NULL);
  46.         if (res)
  47.         {
  48.                 perror("TimerPulse settime Error");
  49.                 return;
  50.         }
  51. }
  52. int main() {
  53.     // startTimer();
  54.     EventSaverTimerInit();
  55.     // 主线程继续执行其他操作
  56.     for (int i = 0; i < 100; ++i) {
  57.         // std::cout << "Main thread doing work: " << i << std::endl;
  58.         std::this_thread::sleep_for(std::chrono::seconds(1));
  59.     }
  60.     // 关闭glog
  61.     google::ShutdownGoogleLogging();
  62.     return 0;
  63. }
复制代码
编译
  1. g++ test.cpp -lrt -lglog
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

兜兜零元

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表