- 论坛徽章:
- 0
|
3。在linux系统下如何用C或者C++编程实现定时器(timer)任务?
参考了别人的程序 ,
其中主要程序如下,
///* ******mytimer.h****************
#ifndef _111_FILE_
#define _111_FILE_
#include <iostream>;
#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>;
#include <stdio.h>;
#include <sys/time.h>;
#include <fstream.h>;
typedef enum { S0_ok,S1_geta} alarm_record_status ;
int SetTimer(int n, int nMode =0);
void TimerRoutine(int signo, siginfo_t* info, void* context);
#endif
//////////////////////////////////////mytimer.cxx
#include "myapp.h"
#define SIGMYTIMER1 (SIGRTMAX)
using namespace std;
int main(int argc,char * argv[])
{
¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£¡£
//
//start timer1
struct sigaction sysact ;
sigemptyset(&sysact.sa_mask);
sysact.sa_flags = SA_SIGINFO;
sysact.sa_sigaction = TimerRoutine1 ;
sigaction(SIGMYTIMER1, &sysact, NULL);
// nTimerFlag=1;
nTimer1ID=SetTimer(milliSecTimer1); //start timer1 as main timer:milliSecTimer1
}
//mode: 0 one time return£¬1£ºperiod return
int SetTimer1(int nElaspe, int nMode=1)
{
struct sigevent evp;
timer_t nTimerID;
evp.sigev_notify = SIGEV_SIGNAL;
evp.sigev_signo = SIGMYTIMER;
evp.sigev_value.sival_ptr = &nTimerID;
int nCreate = timer_create(CLOCK_REALTIME, &evp, &nTimerID);
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(nTimerID, 0, &value, &ovalue) == 0) //success
{
cout<<"Timer id:"<<nTimerID<<" nElaspe:"<<nElaspe<<endl;
}
}
else
{
cout<<"create timer error"<<endl;
}
return nTimerID;
}
void TimerRoutine1(int signo, siginfo_t* info, void* context)
{
if (signo != SIGMYTIMER)
{
return;
}
// do your job here
} |
|