天天看点

linux c语言定时器程序,c语言定时器示例分享

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include "pthread.h"

#include

#include

#include

struct StructOfTimerStatus

{

unsigned int count;                               //计数值

unsigned int flag;                                //定时标志

}

;

struct StructOfTimer

{

struct StructOfTimerStatus      testtime;   //测试定时器

}

mytime;

void SetTimer(int sec,int usec);

void SigalrmFunc(void);

//定时器函数

void SigalrmFunc(void)

{

if(mytime.testtime.count++>20)      //定时1秒,20*50000=1s

{

mytime.testtime.flag=1;

mytime.testtime.count=0;

}

}

void SetTimer(int sec,int usec)

{

struct itimerval value,ovalue;

signal(SIGALRM,(void *)SigalrmFunc);

value.it_value.tv_sec = sec;

value.it_value.tv_usec = usec;

value.it_interval.tv_sec = sec;

value.it_interval.tv_usec = usec;

setitimer(ITIMER_REAL,&value,&ovalue);

}

int main(int argc, char **argv)

{

SetTimer(0, 50000);

while(1)

{

if(mytime.testtime.flag == 1)

{

mytime.testtime.flag = 0;

system("clear");

printf("Timing success\n");

}

}

return 0;

}