linux中创建一个循环定时器(C++)

可以定义一个类来封装定时器的功能,并将其分别放在 `.cpp` 和 `.h` 文件中。这里是一个简化的示例,展示了如何组织这些代码。

假设有一个 `Timer` 类,它负责创建和管理定时器。

Timer.h


#ifndef TIMER_H
#define TIMER_H

#include <signal.h>
#include <time.h>
#include <unistd.h>

class Timer {
public:
    Timer();
    ~Timer();

    void start();
    void stop();

private:
    static void timerCallback(int signum);
    static struct sigaction sa;
    static struct itimerspec its;
    static timer_t timerId;
};

#endif // TIMER_H
```

Timer.cpp



#include "Timer.h"

struct sigaction Timer::sa;
struct itimerspec Timer::its;
timer_t Timer::timerId;

Timer::Timer() {
    // 初始化定时器
    sa.sa_handler = Timer::timerCallback;
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGRTMIN, &sa, NULL) == -1) {
        perror("sigaction");
        exit(1);
    }

    struct sigevent sev;
    sev.sigev_notify = SIGEV_SIGNAL;
    sev.sigev_signo = SIGRTMIN;
    sev.sigev_value.sival_ptr = &Timer::timerId;
    if (timer_create(CLOCK_REALTIME, &sev, &Timer::timerId) == -1) {
        perror("timer_create");
        exit(1);
    }

    its.it_value.tv_sec = 1; // 初始延迟一秒
    its.it_value.tv_nsec = 0;
    its.it_interval.tv_sec = 1; // 每秒触发
    its.it_interval.tv_nsec = 0;
    if (timer_settime(Timer::timerId, 0, &its, NULL) == -1) {
        perror("timer_settime");
        exit(1);
    }
}

Timer::~Timer() {
    // 销毁定时器
    timer_delete(Timer::timerId);
}

void Timer::start() {
    while (true) {
        pause(); // 等待信号
    }
}

void Timer::stop() {
    // 停止定时器
    timer_settime(Timer::timerId, 0, &its, NULL);
}

void Timer::timerCallback(int signum) {
    static int count = 0;
    printf("Timer callback called! Count: %d\n", ++count);
}
```

main.cpp


#include "Timer.h"

int main() {
    Timer timer;
    timer.start();
    // 其他代码...
    return 0;
}
```

`Timer.h` 包含了 `Timer` 类的声明,`Timer.cpp` 实现了类的方法,包括定时器的创建、启动和停止,以及回调函数。`main.cpp` 中包含了主函数,它实例化 `Timer` 对象并开始定时器。

使用时需要注意信号的安全性和正确性。

相关推荐

  1. linux创建循环定时器C++)

    2024-07-18 18:04:01       21 阅读
  2. Linux 创建service并设置开机启动

    2024-07-18 18:04:01       64 阅读
  3. IntelliJ IDEA创建自定义项目向导

    2024-07-18 18:04:01       39 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-18 18:04:01       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-18 18:04:01       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-18 18:04:01       57 阅读
  4. Python语言-面向对象

    2024-07-18 18:04:01       68 阅读

热门阅读

  1. 关于HDFS、Hive和Iceberg

    2024-07-18 18:04:01       20 阅读
  2. Leetcode 3218. Minimum Cost for Cutting Cake I

    2024-07-18 18:04:01       21 阅读
  3. 优选算法之滑动窗口(上)

    2024-07-18 18:04:01       18 阅读
  4. Vite的WebSocket

    2024-07-18 18:04:01       21 阅读
  5. 【面试题】Golang垃圾回收机制(第五篇)

    2024-07-18 18:04:01       21 阅读
  6. 在 Ubuntu上安装 Docker

    2024-07-18 18:04:01       24 阅读
  7. 爬虫的概念

    2024-07-18 18:04:01       21 阅读
  8. Vim 高手指南:Linux 环境下的高级使用技巧

    2024-07-18 18:04:01       17 阅读