linux定时器

来源:互联网 发布:冷兵器吧 知乎 编辑:程序博客网 时间:2024/05/10 09:22
#include <stdio.h>#include <stdlib.h>#include<pthread.h>#include<sys/time.h>#include<unistd.h>#include<signal.h>int count = 0;void set_timer(){        struct itimerval itv, oldtv;        itv.it_interval.tv_sec = 7200;        itv.it_interval.tv_usec = 0;        itv.it_value.tv_sec = 1;        itv.it_value.tv_usec = 0;        setitimer(ITIMER_REAL, &itv, &oldtv);}void sigalrm_handler2(int sig){    printf("time arrived!\n");}void sigalrm_handler(int sig){        count++;        printf("timer signal.. %d\n", count);        time_t timep;        struct tm *p;        time(&timep);        p = localtime(&timep);        printf("%d:%d\n",p->tm_hour,p->tm_min);        // if(p->tm_min == 36&&p->tm_sec==1)        //   {        //   }}void * fun()  {      char *wday[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};      timer_t timep,timep1;      struct tm *p,*p2;      time(&timep);      time(&timep1);      p=gmtime(&timep); //格林威治(GMT)时间      printf("%d%d%d ",(1900+p->tm_year), (1+p->tm_mon),p->tm_mday);      printf("%s %d:%d:%d\n", wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);      p2=localtime(&timep); /*取得当地时间*/      printf ("%d%d%d ", (1900+p2->tm_year),( 1+p2->tm_mon), p2->tm_mday);      printf("%s %d:%d:%d\n", wday[p2->tm_wday],p2->tm_hour, p2->tm_min, p2->tm_sec);     // sleep(2);   /*   while(1)      {     //   usleep(1000);        p2 = localtime(&timep1);        printf("%d",p2->tm_sec);        if(p2->tm_min ==12 )        printf("time arrived!");      }      */        signal(SIGALRM, sigalrm_handler);        set_timer();   //     while (count < 120)   //     {      //      if(count==119)       //        printf("meter reading");     //   }  }int main(){  pthread_t tid;  pthread_create(&tid,NULL,fun,NULL);  void *ret;  pthread_join(tid,&ret);  while(1);  return 0;}

每次启动定时器的时候时间都要重置,关闭定时器时只可以把struct itimerval itv, oldtv置0就可以了。
原创粉丝点击