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` 对象并开始定时器。

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

相关推荐
u0109362652 分钟前
Linux电源管理(五),发热管理(thermal),温度控制 (结合设备树 和ACPI Source Language(ASL)分析)
linux
GreatNXY2 分钟前
【阿里云】阿里云 Ubuntu 服务器无法更新 systemd(Operation not permitted)的解决方法
服务器·阿里云·云计算
itachi-uchiha3 分钟前
Linux上的rm和srm 命令
linux·运维·服务器
Waitccy16 分钟前
Linux 系统安全基线检查:入侵防范测试标准与漏洞修复方法
linux·运维·网络·安全·系统安全·等保
双叶8361 小时前
(C语言)超市管理系统(测试版)(指针)(数据结构)(二进制文件读写)
c语言·开发语言·数据结构·c++
ShiYQ@师1 小时前
Ubuntu 18.04.6下OpenSSL与OpenSSH版本升级
linux·ubuntu
遇见火星1 小时前
Ansible模块——从控制节点向目标主机复制文件!
java·服务器·ansible
带鱼吃猫1 小时前
Linux系统:文件系统前言,详解CHS&LBA地址
linux·运维·服务器
格林威1 小时前
Baumer工业相机堡盟工业相机的工业视觉是否可以在室外可以做视觉检测项目
c++·人工智能·数码相机·计算机视觉·视觉检测
香饽饽~、1 小时前
函数式方法的实现(JDK8+)
java·服务器