Linux C 定时器 篇(四)单线程多定时器

时间:2022-06-03 23:33:22

在平时应用中往往会用到多个定时器,这里我就简单的模拟了一个单线程的多定时器功能。原理是利用settimer()函数提供一个1秒定时器,然后再自己封装成多个定时器。

废话不多说,直接提供代码实例吧!!!

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
static int sec_count; 
int sec = 1;


typedef void (*MyTimerHandle)(void* arg);

typedef struct My_Timer_Args
{
int sec;
MyTimerHandle MTHandle;
}MyTimerArgs;

MyTimerArgs* G_MT[50];
static int TimerCount=0; 


void My_Set_Timer(MyTimerArgs* arg)
{
G_MT[TimerCount] = arg;
TimerCount++;
}

void DealWithSigalrm(int sig)
{   int i;
sec_count++;
for(i=0;i<TimerCount;i++)
{
if((sec_count%(G_MT[i]->sec)) == 0)
G_MT[i]->MTHandle(NULL);
}
}


static void FiveSecondHandle(void* arg)
{
printf("Five Second  count:%d\n",sec_count);
}


static void TenSecondHandle(void* arg)
{
printf("Ten Second count:%d\n",sec_count);
}


int main()
{
struct itimerval value, ovalue, value2;

if(signal(SIGALRM,DealWithSigalrm) == SIG_ERR)
{
puts("error regist sigalrm");
return -1;
}
MyTimerArgs mta1,mta2;


mta1.sec = 5;
mta1.MTHandle = FiveSecondHandle;
mta2.sec =10;
mta2.MTHandle = TenSecondHandle;
My_Set_Timer(&mta1);
My_Set_Timer(&mta2);


value.it_value.tv_sec = sec;
value.it_value.tv_usec = 0;
value.it_interval.tv_sec = sec;
value.it_interval.tv_usec = 0;
setitimer(ITIMER_REAL, &value, &ovalue); //(2)
while(1)
{
//kill(getpid(),SIGALRM);
//raise(SIGALRM);
sleep(sec);
}
  return 0;
}