Linux下定时器的示例代码

简介: Linux下定时器的问题 示例代码: #include using namespace std; #include #include #include ...
Linux下定时器的问题

示例代码:

#include <iostream>
using namespace std;
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <time.h>

#define SIGMYTIMER (SIGRTMAX)

int SetTimer(int nElaspe , int nMode = 1);
void TimerRoutine(int signo, siginfo_t* info, void* context);

int main()
{
cout<<"proc id: "<<(long)getpid()<<" main thread id:"<<pthread_self()<<endl;

struct sigaction sysact;

//setup signal handler
sigemptyset(&sysact.sa_mask);
sysact.sa_flags = SA_SIGINFO;
sysact.sa_sigaction = TimerRoutine ;
sigaction(SIGMYTIMER, &sysact, NULL);

SetTimer(500);
SetTimer(500);
SetTimer(500);

while(1)
{
sleep(1);
}
cout<<"quit!!!!"<<endl;
return 0;
}

timer_t IDList[20]; //use to save timer id;

//mode: 0: oneshot timer; 1: periodicity timer
int SetTimer(int nElaspe, int nMode)
{
struct sigevent evp;

static int nTimerIndex = 0;

evp.sigev_notify = SIGEV_SIGNAL;
evp.sigev_signo = SIGMYTIMER;
evp.sigev_value.sival_ptr = &IDList[nTimerIndex];
int nCreate = timer_create(CLOCK_REALTIME, &evp, &IDList[nTimerIndex]);

if (nCreate == 0) //success
{
struct itimerspec value;
struct itimerspec ovalue;

value.it_value.tv_sec = nElaspe / 1000;
value.it_value.tv_nsec = (nElaspe % 1000) * (1000 * 1000);

if (nMode == 1)
{
value.it_interval.tv_sec = value.it_value.tv_sec;
value.it_interval.tv_nsec = value.it_value.tv_nsec;
}
else
{
value.it_interval.tv_sec = 0;
value.it_interval.tv_nsec = 0;
}

if (timer_settime(IDList[nTimerIndex], 0, &value, &ovalue) == 0) //success
{
cout<<"Timer id:"<<IDList[nTimerIndex]<<" nElaspe:"<<nElaspe<<endl;
}
}
else
{
cout<<"create timer error"<<endl;
}

//++nTimerIndex;
return IDList[nTimerIndex++];
}

//timer singal proc
void TimerRoutine(int signo, siginfo_t* info, void* context)
{
if (signo != SIGMYTIMER) return;

//display time
time_t currtime;
time(&currtime);
tm* pTm = localtime(&currtime);
if (pTm)
{
char sBuf[30];
sprintf(sBuf, "%02d:%02d:%02d", pTm->tm_hour, pTm->tm_min, pTm->tm_sec);
cout<<sBuf;
}

cout<<" timer_id:"<<*(int*)(info->si_value.sival_ptr)<<" sig_id:"<<signo<<" thread_id:"<<pthread_self()<<endl;
}

编译:

librt是一个系统库,你不必管他的路径(在usr/lib中),在编译时记得连接就行了。

g++ -o demo demo.cpp -lrt
 
目录
相关文章
|
Shell Apache
77Linux - crontab定时器
77Linux - crontab定时器
159 0
|
监控 Linux 编译器
Linux C++ 定时器任务接口深度解析: 从理论到实践
Linux C++ 定时器任务接口深度解析: 从理论到实践
574 2
|
Linux
手把手教你写Linux设备驱动---定时器(一)(基于友善之臂4412开发板)
手把手教你写Linux设备驱动---定时器(一)(基于友善之臂4412开发板)
372 0
Linux驱动中断与时间篇——高精度定时器hrtimer
Linux驱动中断与时间篇——高精度定时器hrtimer
Linux驱动中断与时间篇——低分辨率定时器
Linux驱动中断与时间篇——低分辨率定时器
|
存储 Linux 调度
Linux驱动开发——定时器
Linux驱动开发——定时器
390 0
Linux驱动开发——定时器
|
Linux 芯片
Linux系统中裸机定时器的基本原理
大家好,今天的话主要和大家聊一聊,如何使用定时器,完成精准的定时功能实现​。
333 0
Linux系统中裸机定时器的基本原理
|
数据采集 前端开发 JavaScript
【Linux】好用的定时器
【Linux】好用的定时器
269 0
【Linux】好用的定时器
Linux定时器
内核中使用jiffies进行时间计数,计数的频率由HZ来决定